@spzxg/cli-skill 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,17 +2,28 @@
2
2
 
3
3
  中枢 CLI Task Center 的独立 API 客户端、命令行和可安装 Skill。业务系统通过它把工作交给已配置的远端 CLI Agent,支持一次性多任务拆解、依赖关系、派发即返回、等待结果和节点 ego 浏览器开关。只调用现有 HTTP API,不修改中枢服务、调度器或 Operator。
4
4
 
5
+ **0.1.1 已发布到 npm**,包含普通对话的执行配置、能力读取和按修订号保存。当前源码为 **0.1.2 本地候选**,仅修正文档与版本标识,功能与 0.1.1 相同;不会覆盖已发布版本。执行配置需要配套中枢迁移和节点升级,安装本包不会完成这些服务端步骤。可与已发布的 `@spzxg/cli-ui@0.6.9` 协同使用,各包版本独立。
6
+
5
7
  ## 安装 Skill
6
8
 
7
- 要求 Node.js 22+。包发布后执行:
9
+ 要求 Node.js 22+。以下安装示例固定使用已核验发布的 0.1.1,支持本文全部命令:
8
10
 
9
11
  ```bash
10
- npx -y @spzxg/cli-skill@0.1.0 install --agent codex
11
- npx -y @spzxg/cli-skill@0.1.0 install --agent claude
12
+ npx -y @spzxg/cli-skill@0.1.1 install --agent codex
13
+ npx -y @spzxg/cli-skill@0.1.1 install --agent claude
12
14
  # 或同时安装到两者
13
- npx -y @spzxg/cli-skill@0.1.0 install --agent all
15
+ npx -y @spzxg/cli-skill@0.1.1 install --agent all
14
16
  ```
15
17
 
18
+ 验收 0.1.2 时安装本地候选 tarball,并用同版本命令安装 Skill:
19
+
20
+ ```bash
21
+ npm install -g /path/to/spzxg-cli-skill-0.1.2.tgz
22
+ cli-skill install --agent codex
23
+ ```
24
+
25
+ 0.1.2 尚未发布,当前公开 npm 命令继续使用 0.1.1。历史版本 0.1.0 不支持执行配置命令或 `execution_config` 字段。
26
+
16
27
  默认安装到 `~/.codex/skills/cli-task-center` 或 `~/.claude/skills/cli-task-center`;Codex 尊重 `CODEX_HOME`。自定义宿主用 `install --dir /path/to/skills`。已有目录时明确报错;确认替换本 Skill 时加 `--force`。无 npm 安装后脚本,不自动修改任何宿主配置。安装后按宿主的技能刷新方式加载,或重开会话。
17
28
 
18
29
  ## 配置 API
@@ -39,12 +50,12 @@ Base URL 是中枢根地址;也支持业务代理前缀,例如 `https://busi
39
50
 
40
51
  ```bash
41
52
  # 接受后立即返回 IDs,不后台轮询
42
- npx -y @spzxg/cli-skill@0.1.0 dispatch --input job.json
53
+ npx -y @spzxg/cli-skill@0.1.1 dispatch --input job.json
43
54
  # 接受后等待,最多 60 秒
44
- npx -y @spzxg/cli-skill@0.1.0 dispatch --input job.json --wait --timeout-seconds 60
55
+ npx -y @spzxg/cli-skill@0.1.1 dispatch --input job.json --wait --timeout-seconds 60
45
56
  # 延续已有任务的等待,不新建任务
46
- npx -y @spzxg/cli-skill@0.1.0 wait <job_id> --timeout-seconds 60
47
- npx -y @spzxg/cli-skill@0.1.0 get <job_id>
57
+ npx -y @spzxg/cli-skill@0.1.1 wait <job_id> --timeout-seconds 60
58
+ npx -y @spzxg/cli-skill@0.1.1 get <job_id>
48
59
  ```
49
60
 
50
61
  也支持 `--input -` 从 stdin 读取 JSON。`--browser true|false` 覆盖整个提交中的子任务;省略时保留每个 `tasks[].browser`,缺省 false。true 由现有服务在执行节点准备 ego 浏览器,本机不会启动浏览器。
@@ -79,6 +90,39 @@ npx -y @spzxg/cli-skill@0.1.0 get <job_id>
79
90
 
80
91
  CLI stdout 是 JSON;请求错误在 stderr。退出码:0 接受/成功,1 请求错误/任务失败,2 等待超时,3 取消,4 需要输入。
81
92
 
93
+ ## 对话执行配置(0.1.1 起)
94
+
95
+ 先读取服务端能力目录,选择其中可用的智能体及其模型、推理和权限选项。具体 ID 由中枢配置,不能把显示名称或未经支持的模型硬编码进请求。配置读取与保存各发起一个短 HTTP 请求,不后台轮询。
96
+
97
+ ```bash
98
+ # 新对话可选能力与默认值
99
+ cli-skill execution-config
100
+ # 已有 Job 中的指定对话;省略 task-id 时定位最早的对话
101
+ cli-skill execution-config job_123 --task-id task_456
102
+ # settings.json 只放 agent/model/reasoning/permission_mode;revision 使用刚刚读取的值
103
+ cli-skill set-execution-config job_123 --task-id task_456 --input settings.json --expected-revision 3
104
+ ```
105
+
106
+ 响应包含 `revision`、`agent`、`model`、`reasoning`、`permission_mode` 和 `agents` 能力目录。模型、推理、权限字段传 `null` 表示恢复默认;省略表示保存时不修改。切换智能体时,未显式提供的三个选项会恢复新智能体的默认值。`execution_config.agent` 是目录中的具体 ID,不接受 `system` 或 `null`。
107
+
108
+ 创建对话可在首条任务中附带配置,无需先创建再保存;只适用于 `mode: "conversation"`,一次性任务仍按原有产品线配置运行。显式传入配置时,客户端先读取并验证能力接口,再提交一次创建请求;旧服务缺少能力接口或返回无效配置时不创建任务,避免旧服务忽略字段后按错误模式执行。不传配置时仍仅提交一次创建请求:
109
+
110
+ ```json
111
+ {
112
+ "title": "检查报告",
113
+ "mode": "conversation",
114
+ "tasks": [{
115
+ "title": "检查报告",
116
+ "prompt": "阅读报告,先提出修改方案。",
117
+ "execution_config": {"agent": "codex", "model": null, "reasoning": null, "permission_mode": "plan"}
118
+ }]
119
+ }
120
+ ```
121
+
122
+ 示例中的 `codex`、`plan` 必须以实际目录确认支持后使用;若同时给 `tasks[].agent`,应与配置里的智能体一致,或使用既有 `system` 继承别名。保存设置不会发送消息或启动 AI,待后续轮次执行时应用。只允许空闲且没有排队消息的对话保存。
123
+
124
+ 收到 `409 execution_config_conflict` 时重新读取并核对用户意图,不能覆盖别处的新设置;`409 execution_config_busy` 时待当前轮次和队列结束,再读取。网络错误、5xx 或非法成功响应可能返回 `uncertain: true`,表示保存结果未确认;先对同一 `job_id`/`task_id` 重新读取,禁止自动重发 PATCH。旧服务缺少接口或能力时明确失败,不伪造保存成功,也不自动改用另一种执行模式。
125
+
82
126
  ## 后端 JavaScript / TypeScript
83
127
 
84
128
  ```js
@@ -90,7 +134,17 @@ const result = await center.waitForJob(receipt.job_id, { timeout_seconds: 60 });
90
134
  // 或 await center.dispatchAndWait(job, { browser: true, timeout_seconds: 60 });
91
135
  ```
92
136
 
93
- 导出 `createClient({baseUrl, token, request_timeout_seconds?})`、`createClientFromEnv()`、`validateJob()`、`CenterApiError`,附 TypeScript 声明。支持 `AbortSignal`,请求默认 30 秒超时、不跟随重定向、不自动重试 POST。查询失败会携带已知 `job_id`;提交响应不确定时 `uncertain: true`,须先在中枢对账,不能直接重建任务。客户端校验常用字段、依赖图和会被服务忽略的错误模式,细节校验仍以现有服务为准。
137
+ 0.1.1 SDK 也提供同一配置链路:
138
+
139
+ ```js
140
+ const defaults = await center.getExecutionConfig();
141
+ const current = await center.getExecutionConfig('job_123', { task_id: 'task_456' });
142
+ const saved = await center.setExecutionConfig('job_123', { model: null }, {
143
+ task_id: 'task_456', expected_revision: current.revision,
144
+ });
145
+ ```
146
+
147
+ 导出 `createClient({baseUrl, token, request_timeout_seconds?})`、`createClientFromEnv()`、`validateJob()`、`CenterApiError`,附 TypeScript 声明。支持 `AbortSignal`,请求默认 30 秒超时、不跟随重定向、不自动重试 POST/PATCH。等待查询失败和配置保存失败携带已知 `job_id`;写入响应不确定时 `uncertain: true`,须先在中枢对账,不能直接重建任务或重复保存。错误仅保留状态和已知错误码,不回显任意服务端错误正文。客户端校验常用字段、依赖图和会被服务忽略的错误模式,细节校验仍以现有服务为准。
94
148
 
95
149
  需要回调时原样传 `callback: {url, code}`。业务消费方应核对 Bearer code,并按 API 的事件标识/版本去重。令牌和 callback code 仅由业务配置提供;不要提交到代码仓库或打印请求体。
96
150
 
package/bin/cli-skill.js CHANGED
@@ -4,7 +4,7 @@ import { readFile } from 'node:fs/promises';
4
4
  import { createClientFromEnv } from '../src/client.js';
5
5
  import { installSkill } from '../src/install.js';
6
6
 
7
- const help = `CLI Task Center · @spzxg/cli-skill 0.1.0
7
+ const help = `CLI Task Center · @spzxg/cli-skill 0.1.2
8
8
 
9
9
  Install an agent skill:
10
10
  cli-skill install [--agent codex|claude|all] [--dir <skills-directory>] [--force]
@@ -14,29 +14,39 @@ Use the existing Center HTTP API:
14
14
  cli-skill get <job_id>
15
15
  cli-skill wait <job_id> [--turn-id <turn_id>]
16
16
  Wait options: --timeout-seconds <60> --poll-interval-seconds <3>
17
+ cli-skill execution-config [job_id] [--task-id <task_id>]
18
+ cli-skill set-execution-config <job_id> --input <settings.json|-> --expected-revision <revision> [--task-id <task_id>]
17
19
 
18
20
  API commands require CLI_CENTER_BASE_URL and CLI_CENTER_TOKEN (product-line token).
19
21
  Dispatch returns the API receipt. --wait returns a bounded wait result as JSON.
20
22
  Browser true requests ego on the execution node. No local browser is launched.
21
23
  Timeout leaves remote work running; use wait with the same IDs. Never resubmit blindly.
24
+ Execution settings require the upgraded Center/node. Read first; a failed save is not automatically retried.
22
25
  Exit: 0 success/accepted, 1 error/failed, 2 waiting timeout, 3 cancelled, 4 needs input.
23
26
  `;
24
27
  const write = value => process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
28
+ async function readInput(path) {
29
+ if (path !== '-') return JSON.parse(await readFile(path, 'utf8'));
30
+ let raw = ''; for await (const chunk of process.stdin) raw += chunk;
31
+ return JSON.parse(raw);
32
+ }
25
33
  try {
26
34
  const { values, positionals } = parseArgs({ allowPositionals: true, strict: true, options: {
27
35
  input: { type: 'string' }, browser: { type: 'string' }, wait: { type: 'boolean' },
28
36
  agent: { type: 'string' }, dir: { type: 'string' }, force: { type: 'boolean' },
29
37
  'timeout-seconds': { type: 'string' }, 'poll-interval-seconds': { type: 'string' },
30
38
  'turn-id': { type: 'string' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' },
39
+ 'task-id': { type: 'string' }, 'expected-revision': { type: 'string' },
31
40
  } });
32
- if (values.version) { process.stdout.write('0.1.0\n'); }
41
+ if (values.version) { process.stdout.write('0.1.2\n'); }
33
42
  else if (values.help || !positionals.length) { process.stdout.write(help); }
34
43
  else {
35
44
  const [command, id, ...extra] = positionals;
36
- if (extra.length || !['install', 'dispatch', 'get', 'wait'].includes(command)) throw new TypeError('Unknown command or unexpected positional argument; use --help');
45
+ if (extra.length || !['install', 'dispatch', 'get', 'wait', 'execution-config', 'set-execution-config'].includes(command)) throw new TypeError('Unknown command or unexpected positional argument; use --help');
37
46
  const allowed = {
38
47
  install: ['agent', 'dir', 'force'], dispatch: ['input', 'browser', 'wait', 'timeout-seconds', 'poll-interval-seconds'],
39
48
  get: [], wait: ['turn-id', 'timeout-seconds', 'poll-interval-seconds'],
49
+ 'execution-config': ['task-id'], 'set-execution-config': ['input', 'expected-revision', 'task-id'],
40
50
  }[command];
41
51
  for (const key of Object.keys(values)) if (!allowed.includes(key)) throw new TypeError(`--${key} is not valid for ${command}`);
42
52
  if (command === 'install') {
@@ -55,11 +65,13 @@ try {
55
65
  if (command === 'dispatch') {
56
66
  if (id || !values.input) throw new TypeError('dispatch requires --input <job.json|->');
57
67
  if (!values.wait && (values['timeout-seconds'] !== undefined || values['poll-interval-seconds'] !== undefined)) throw new TypeError('Wait options require --wait');
58
- let raw;
59
- if (values.input === '-') { raw = ''; for await (const chunk of process.stdin) raw += chunk; }
60
- else raw = await readFile(values.input, 'utf8');
61
- const job = JSON.parse(raw);
68
+ const job = await readInput(values.input);
62
69
  result = await (values.wait ? client.dispatchAndWait(job, opts) : client.dispatch(job, opts));
70
+ } else if (command === 'execution-config') {
71
+ result = await client.getExecutionConfig(id, { task_id: values['task-id'] });
72
+ } else if (command === 'set-execution-config') {
73
+ if (!id || !values.input || !/^\d+$/.test(values['expected-revision'] ?? '')) throw new TypeError('set-execution-config requires job_id, --input and --expected-revision from the last read');
74
+ result = await client.setExecutionConfig(id, await readInput(values.input), { task_id: values['task-id'], expected_revision: Number(values['expected-revision']) });
63
75
  } else {
64
76
  if (!id) throw new TypeError(`${command} requires a job_id`);
65
77
  result = await (command === 'get' ? client.getJob(id) : client.waitForJob(id, opts));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spzxg/cli-skill",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "CLI Task Center API client and installable agent skill: dispatch background tasks, wait for results, split dependent work, and enable execution-node ego browsers.",
5
5
  "type": "module",
6
6
  "engines": { "node": ">=22" },
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: cli-task-center
3
- description: Delegate work to an existing CLI Task Center through its HTTP API. Use to submit background jobs, split work into dependent CLI tasks, wait for task or conversation-turn results, and request the execution node's ego browser. Requires a configured Center URL and product-line token.
3
+ description: Delegate work to an existing CLI Task Center through its HTTP API. Use to submit jobs, split dependent tasks, wait for results, request the execution node's ego browser, or inspect and change conversation execution settings. Requires a configured Center URL and product-line token.
4
4
  ---
5
5
 
6
6
  # CLI Task Center
@@ -11,7 +11,7 @@ Use this skill when the user wants work executed by their configured Center and
11
11
 
12
12
  Commands require Node.js 22+ and two environment variables: `CLI_CENTER_BASE_URL` (Center root or business backend proxy URL, without a trailing `/api`) and `CLI_CENTER_TOKEN` (product-line token). The credential stays in the environment; never place it in prompts, JSON job files, skill files, or published artifacts. Do not read an admin token to supply missing product-line configuration.
13
13
 
14
- Use `npx -y @spzxg/cli-skill@0.1.0` followed by the command below. A global installation also provides `cli-skill`.
14
+ This Skill accompanies the `@spzxg/cli-skill@0.1.2` documentation/version correction candidate; its commands are unchanged from the published 0.1.1. For the published package, use `npx -y @spzxg/cli-skill@0.1.1` followed by a command below, or an installed 0.1.1 `cli-skill`. To validate the 0.1.2 candidate, use the matching installed command from its local tarball; 0.1.2 is not yet published. Version 0.1.0 lacks the execution-settings commands. Settings still require the matching Center migration and node upgrade; installing the client does not deploy services or migrate a database.
15
15
 
16
16
  ## Choose the user's completion contract
17
17
 
@@ -40,6 +40,17 @@ Translate the request into concrete prompts with inputs, intended outputs, accep
40
40
 
41
41
  Preserve supplied `business_id` for business correlation; initial Job creation is **not idempotent**. Use supported `done_when` rules only when the request needs them; otherwise the Center's `agent_confirm` default applies. `manual` may wait indefinitely for human confirmation, so do not use it for unattended automation. Agent names and effective agent selection are configured by the Center; omit `agent` or use `system` to inherit its configured product-line plan.
42
42
 
43
+ ## Conversation execution settings
44
+
45
+ When the user requests a particular agent, model, reasoning level or execution mode, read `cli-skill execution-config` for new-conversation capabilities. Use available IDs from the returned `agents` catalog, not display labels or a hardcoded model list. Without a requested override, preserve the normal product-line defaults.
46
+
47
+ - **First turn:** only for `mode: "conversation"`, put the selected values in `tasks[0].execution_config`, for example `{"agent":"codex","permission_mode":"plan"}` after confirming those IDs are available. An explicit `tasks[0].agent` must match, or be `system`. One-shot jobs do not accept execution settings. When settings are supplied, the client checks the capability endpoint before creating work; an unavailable or invalid response stops creation. Do not remove the requested settings just to bypass that failure.
48
+ - **Existing conversation:** read `cli-skill execution-config <job_id> --task-id <task_id>`, then save with `cli-skill set-execution-config <job_id> --task-id <task_id> --input settings.json --expected-revision <returned_revision>`. Keep the same task ID throughout; omitting it targets the earliest conversation in the Job. The settings file contains only `agent`, `model`, `reasoning`, `permission_mode`; stdin via `--input -` also works. Saving does not send a message or start AI work.
49
+
50
+ Model, reasoning and permission accept `null` to restore defaults; omitted fields stay unchanged during a save. Switching agent resets omitted options to the new agent's defaults. `execution_config.agent` must be a concrete catalog ID, not `system` or `null`. The service permits saving only while the conversation and queue are idle.
51
+
52
+ Reads and saves are single short HTTP calls, without background polling or automatic write retries. On `execution_config_conflict`, read again and reconcile the new settings with the user's intent; do not overwrite a concurrent change blindly. On `execution_config_busy`, wait for the active/queued work to finish before reading again. If saving reports `uncertain: true`, first read the same conversation to establish whether it was applied. An unavailable endpoint or capability is not a successful save and must not silently change the requested mode.
53
+
43
54
  ## Browser capability
44
55
 
45
56
  Set `tasks[].browser: true` for tasks that need the execution node's ego browser, and include the starting URL and site work in the prompt. Default is false. `--browser true` or `--browser false` overrides **all** tasks in that submission; omit the flag for a mix. This requests a task browser on the remote node, not on the caller's machine. Availability depends on the node's existing configuration.
@@ -51,7 +62,7 @@ When a website requires login, verification, or user input, report `needs_input`
51
62
  - `outcome: succeeded|failed|cancelled` and `completed: true`: the awaited object reached a terminal state. Preserve failure details and artifact references from the API.
52
63
  - `outcome: needs_input`: the API reports a question or observed user-input wait. Return it to the user; do not count it as successful delivery of the requested work.
53
64
  - `outcome: timeout`, `timed_out: true`: only local waiting ended. Remote work continues. Return the IDs and resume with `wait` if requested. Do not cancel, close, or create a replacement job.
54
- - HTTP/network errors: CLI writes structured JSON to stderr. After submission uncertainty, do not automatically retry POST; reconcile the original request in the Center. After a query error with a known `job_id`, query/wait that same ID. Never replace an existing job just to recover a wait.
65
+ - HTTP/network errors: CLI writes structured JSON to stderr. After write uncertainty, do not automatically retry POST/PATCH; reconcile the original request in the Center. After a query error with a known `job_id`, query/wait that same ID. Never replace an existing job just to recover a wait.
55
66
 
56
67
  CLI exit codes: 0 accepted/succeeded, 1 request error/failed, 2 wait timeout, 3 cancelled, 4 needs input. Parse stdout JSON for the actual API status and outcome.
57
68
 
package/src/client.d.ts CHANGED
@@ -1,7 +1,16 @@
1
1
  export interface Callback { url: string; code: string }
2
2
  export type DoneWhen = { kind: 'http'; url: string; json_path: string; done?: unknown[]; failed?: unknown[] } | { kind: 'git_diff' | 'agent_confirm' | 'manual' } | { kind: 'all'; rules: DoneWhen[] };
3
+ export interface ExecutionOptions { agent?: string; model?: string | null; reasoning?: string | null; permission_mode?: string | null }
4
+ export interface ExecutionOption { value: string; label: string; sub?: string; group?: string }
5
+ export interface ExecutionConfiguration {
6
+ revision: number; agent: string; model: string | null; reasoning: string | null; permission_mode: string | null;
7
+ agents: Array<{ id: string; label: string; disabled: boolean; capabilities: { models: ExecutionOption[]; reasoningOptions: ExecutionOption[]; permissionModes: ExecutionOption[]; supportsCustomModels: boolean }; defaults: Omit<ExecutionOptions, 'agent'> }>;
8
+ }
9
+ export interface ExecutionTarget { task_id?: string; signal?: AbortSignal }
3
10
  export interface TaskInput {
4
11
  title: string; prompt: string; key?: string; business_id?: string; agent?: string;
12
+ /** Only supported when JobInput.mode is conversation. */
13
+ execution_config?: ExecutionOptions;
5
14
  depends_on?: string[]; done_when?: DoneWhen; timeout_seconds?: number; browser?: boolean;
6
15
  browser_playbook?: string; browser_pacing?: unknown; browser_learn?: { callback: Callback };
7
16
  callback?: Callback; workspace?: Record<string, unknown>;
@@ -34,6 +43,8 @@ export interface CenterClient {
34
43
  getJob(id: string, options?: {signal?: AbortSignal}): Promise<JobView>;
35
44
  getTurn(jobId: string, turnId: string, options?: {signal?: AbortSignal}): Promise<TurnView>;
36
45
  waitForJob(id: string, options?: WaitOptions): Promise<WaitResult>;
46
+ getExecutionConfig(jobId?: string, options?: ExecutionTarget): Promise<ExecutionConfiguration>;
47
+ setExecutionConfig(jobId: string, changes: ExecutionOptions, options: ExecutionTarget & { expected_revision: number }): Promise<ExecutionConfiguration>;
37
48
  }
38
49
  export class CenterApiError extends Error { status?: number; code?: string; job_id?: string; uncertain: boolean; receipt?: DispatchReceipt }
39
50
  export function validateJob(input: JobInput, options?: DispatchOptions): JobInput;
package/src/client.js CHANGED
@@ -3,6 +3,7 @@ import { setTimeout as delay } from 'node:timers/promises';
3
3
  const terminal = new Set(['succeeded', 'failed', 'cancelled']);
4
4
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
5
5
  const nonempty = value => typeof value === 'string' && value.trim().length > 0;
6
+ const executionErrors = new Set(['invalid_execution_config', 'execution_config_conflict', 'execution_config_busy', 'execution_config_unavailable', 'execution_config_not_supported', 'execution_agent_conflict', 'execution_agent_unavailable', 'execution_account_unavailable', 'conversation_closed', 'conversation_not_found', 'not_found']);
6
7
  function requireValue(condition, message) { if (!condition) throw new TypeError(message); }
7
8
  function range(value, min, max, name) {
8
9
  requireValue(typeof value === 'number' && Number.isFinite(value) && value >= min && value <= max, `${name} must be between ${min} and ${max}`);
@@ -21,6 +22,29 @@ function judge(value) {
21
22
  value.rules.forEach(judge);
22
23
  }
23
24
  }
25
+ function executionConfig(value) {
26
+ requireValue(object(value), 'execution_config must be an object');
27
+ const result = {};
28
+ for (const [key, item] of Object.entries(value)) {
29
+ requireValue(['agent', 'model', 'reasoning', 'permission_mode'].includes(key), `Unsupported execution_config field: ${key}`);
30
+ if (item === undefined) continue;
31
+ if (key === 'agent') {
32
+ requireValue(nonempty(item) && item !== 'system', 'execution_config.agent must be a concrete agent from the capability catalog');
33
+ result[key] = item;
34
+ } else {
35
+ requireValue(item === null || (nonempty(item) && item.trim().length <= 2048 && !/[\x00-\x1f\x7f]/.test(item.trim())), `execution_config.${key} must be null or a nonempty value of at most 2048 characters`);
36
+ result[key] = item === null ? null : item.trim();
37
+ }
38
+ }
39
+ return result;
40
+ }
41
+ function executionReply(value, uncertain = false) {
42
+ if (!object(value) || !Number.isSafeInteger(value.revision) || value.revision < 0 || !nonempty(value.agent) || !Array.isArray(value.agents)
43
+ || ['model', 'reasoning', 'permission_mode'].some(key => value[key] !== null && typeof value[key] !== 'string')) {
44
+ throw new CenterApiError('Center returned invalid execution settings; read the settings again before continuing.', { code: 'invalid_execution_config_response', uncertain });
45
+ }
46
+ return value;
47
+ }
24
48
 
25
49
  /** Validate wrapper-sensitive fields; the Center remains the API authority. */
26
50
  export function validateJob(input, options = {}) {
@@ -39,7 +63,7 @@ export function validateJob(input, options = {}) {
39
63
  const keys = new Map();
40
64
  const tasks = input.tasks.map((task, index) => {
41
65
  requireValue(object(task) && nonempty(task.title) && typeof task.prompt === 'string', `tasks[${index}] requires title and prompt`);
42
- const fields = new Set(['key', 'business_id', 'title', 'prompt', 'agent', 'depends_on', 'done_when', 'timeout_seconds', 'browser', 'browser_playbook', 'browser_pacing', 'browser_learn', 'callback', 'workspace']);
66
+ const fields = new Set(['key', 'business_id', 'title', 'prompt', 'agent', 'execution_config', 'depends_on', 'done_when', 'timeout_seconds', 'browser', 'browser_playbook', 'browser_pacing', 'browser_learn', 'callback', 'workspace']);
43
67
  for (const key of Object.keys(task)) requireValue(fields.has(key), `Unsupported task field: ${key}`);
44
68
  if (task.key !== undefined) requireValue(nonempty(task.key), 'task.key must be nonempty');
45
69
  const key = task.key ?? `__seq_${index}`;
@@ -49,6 +73,12 @@ export function validateJob(input, options = {}) {
49
73
  if (task.done_when !== undefined) judge(task.done_when);
50
74
  if (task.timeout_seconds !== undefined) requireValue(Number.isInteger(task.timeout_seconds) && task.timeout_seconds > 0, 'task.timeout_seconds must be a positive integer');
51
75
  if (task.agent !== undefined) requireValue(nonempty(task.agent), 'task.agent must be nonempty');
76
+ let execution;
77
+ if (task.execution_config !== undefined) {
78
+ requireValue(input.mode === 'conversation', 'execution_config requires conversation mode');
79
+ execution = executionConfig(task.execution_config);
80
+ requireValue(!execution.agent || !task.agent || task.agent === 'system' || task.agent === execution.agent, 'task.agent and execution_config.agent must match');
81
+ }
52
82
  if (task.business_id !== undefined) requireValue(nonempty(task.business_id), 'task.business_id must be nonempty');
53
83
  if (task.callback !== undefined) callback(task.callback);
54
84
  const browser = options.browser ?? task.browser ?? false;
@@ -59,7 +89,7 @@ export function validateJob(input, options = {}) {
59
89
  requireValue(task.done_when === undefined && task.depends_on === undefined, 'conversation does not accept done_when or depends_on');
60
90
  requireValue(task.browser_learn === undefined, 'conversation does not accept browser_learn');
61
91
  }
62
- return { ...task, browser };
92
+ return { ...task, browser, ...(execution ? { execution_config: execution } : {}) };
63
93
  });
64
94
  const visiting = new Set();
65
95
  const visited = new Set();
@@ -92,6 +122,7 @@ export function createClient({ baseUrl, token, request_timeout_seconds = 30, fet
92
122
  const prefix = base.href.replace(/\/+$/, '');
93
123
  async function request(path, { method = 'GET', body, signal } = {}) {
94
124
  signal?.throwIfAborted();
125
+ const mutation = method === 'POST' || method === 'PATCH';
95
126
  const requestSignal = AbortSignal.any([AbortSignal.timeout(Math.ceil(request_timeout_seconds * 1000)), ...(signal ? [signal] : [])]);
96
127
  let response;
97
128
  try {
@@ -100,12 +131,16 @@ export function createClient({ baseUrl, token, request_timeout_seconds = 30, fet
100
131
  headers: { authorization: `Bearer ${token}`, accept: 'application/json', ...(body ? { 'content-type': 'application/json' } : {}) },
101
132
  ...(body ? { body: JSON.stringify(body) } : {}),
102
133
  });
103
- if (!response.ok) throw new CenterApiError(`Center API returned HTTP ${response.status}`, { status: response.status, code: 'http_error', uncertain: method === 'POST' && response.status >= 500 });
134
+ if (!response.ok) {
135
+ const failure = await response.json().catch(() => null);
136
+ const code = executionErrors.has(failure?.error) ? failure.error : 'http_error';
137
+ throw new CenterApiError(`Center API returned HTTP ${response.status}`, { status: response.status, code, uncertain: mutation && response.status >= 500 });
138
+ }
104
139
  return await response.json();
105
140
  } catch (error) {
106
141
  if (error instanceof CenterApiError) throw error;
107
- if (signal?.aborted && method !== 'POST') throw signal.reason;
108
- throw new CenterApiError(method === 'POST' ? 'Submission outcome is unknown; do not automatically resubmit. Reconcile with the Center before retrying.' : 'Center API request failed; retry the query using the same job_id.', { code: 'request_failed', uncertain: method === 'POST' });
142
+ if (signal?.aborted && !mutation) throw signal.reason;
143
+ throw new CenterApiError(mutation ? 'Write outcome is unknown; do not automatically resubmit. Read the current state from the Center before retrying.' : 'Center API request failed; retry the same query.', { code: 'request_failed', uncertain: mutation });
109
144
  }
110
145
  }
111
146
  const idPath = id => { requireValue(nonempty(id) && id.length <= 128, 'A valid id is required'); return encodeURIComponent(id); };
@@ -117,8 +152,37 @@ export function createClient({ baseUrl, token, request_timeout_seconds = 30, fet
117
152
  }
118
153
  async function getJob(id, options = {}) { return request(`/api/jobs/${idPath(id)}`, options); }
119
154
  async function getTurn(id, turnId, options = {}) { return request(`/api/jobs/${idPath(id)}/turns/${idPath(turnId)}`, options); }
155
+ function executionPath(jobId, taskId) {
156
+ if (jobId === undefined) {
157
+ requireValue(taskId === undefined, 'task_id requires job_id');
158
+ return '/api/execution-config';
159
+ }
160
+ let path = `/api/jobs/${idPath(jobId)}/execution-config`;
161
+ if (taskId !== undefined) {
162
+ requireValue(nonempty(taskId) && taskId.length <= 64, 'task_id must be a nonempty string of at most 64 characters');
163
+ path += `?task_id=${encodeURIComponent(taskId)}`;
164
+ }
165
+ return path;
166
+ }
167
+ async function getExecutionConfig(jobId, options = {}) {
168
+ return executionReply(await request(executionPath(jobId, options.task_id), { signal: options.signal }));
169
+ }
170
+ async function setExecutionConfig(jobId, changes, options = {}) {
171
+ idPath(jobId);
172
+ requireValue(Number.isSafeInteger(options.expected_revision) && options.expected_revision >= 0, 'expected_revision must be a nonnegative safe integer from the last read');
173
+ const body = { ...executionConfig(changes), expected_revision: options.expected_revision };
174
+ try {
175
+ return executionReply(await request(executionPath(jobId, options.task_id), { method: 'PATCH', body, signal: options.signal }), true);
176
+ } catch (error) {
177
+ if (error instanceof CenterApiError) error.job_id = jobId;
178
+ throw error;
179
+ }
180
+ }
120
181
  async function dispatch(input, options = {}) {
121
- const receipt = await request('/api/jobs', { method: 'POST', body: validateJob(input, options), signal: options.signal });
182
+ const body = validateJob(input, options);
183
+ // Older Centers can silently discard unknown task fields. Check support before creating work with explicit settings.
184
+ if (body.tasks.some(task => task.execution_config !== undefined)) await getExecutionConfig(undefined, { signal: options.signal });
185
+ const receipt = await request('/api/jobs', { method: 'POST', body, signal: options.signal });
122
186
  if (!object(receipt) || !nonempty(receipt.job_id ?? receipt.id)) throw new CenterApiError('Center returned no job_id; reconcile submission before retrying', {code:'invalid_receipt', uncertain:true});
123
187
  return receipt;
124
188
  }
@@ -171,7 +235,7 @@ export function createClient({ baseUrl, token, request_timeout_seconds = 30, fet
171
235
  throw error;
172
236
  }
173
237
  }
174
- return { dispatch, dispatchAndWait, getJob, getTurn, waitForJob };
238
+ return { dispatch, dispatchAndWait, getJob, getTurn, waitForJob, getExecutionConfig, setExecutionConfig };
175
239
  }
176
240
 
177
241
  export function createClientFromEnv(env = process.env) {