@spzxg/cli-skill 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +96 -2
- package/bin/cli-skill.js +74 -0
- package/package.json +17 -4
- package/skills/cli-task-center/SKILL.md +58 -0
- package/src/client.d.ts +41 -0
- package/src/client.js +179 -0
- package/src/install.js +38 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 spzxg
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,97 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @spzxg/cli-skill
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
中枢 CLI Task Center 的独立 API 客户端、命令行和可安装 Skill。业务系统通过它把工作交给已配置的远端 CLI Agent,支持一次性多任务拆解、依赖关系、派发即返回、等待结果和节点 ego 浏览器开关。只调用现有 HTTP API,不修改中枢服务、调度器或 Operator。
|
|
4
|
+
|
|
5
|
+
## 安装 Skill
|
|
6
|
+
|
|
7
|
+
要求 Node.js 22+。包发布后执行:
|
|
8
|
+
|
|
9
|
+
```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
|
+
# 或同时安装到两者
|
|
13
|
+
npx -y @spzxg/cli-skill@0.1.0 install --agent all
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
默认安装到 `~/.codex/skills/cli-task-center` 或 `~/.claude/skills/cli-task-center`;Codex 尊重 `CODEX_HOME`。自定义宿主用 `install --dir /path/to/skills`。已有目录时明确报错;确认替换本 Skill 时加 `--force`。无 npm 安装后脚本,不自动修改任何宿主配置。安装后按宿主的技能刷新方式加载,或重开会话。
|
|
17
|
+
|
|
18
|
+
## 配置 API
|
|
19
|
+
|
|
20
|
+
以下变量用于本机 CLI、后端 SDK 或 MCP 服务进程,不放进前端:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
export CLI_CENTER_BASE_URL='https://cli.xgjktech.com.cn'
|
|
24
|
+
export CLI_CENTER_TOKEN='<产品线令牌>'
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Base URL 是中枢根地址;也支持业务代理前缀,例如 `https://business.example/api/center`,客户端会追加 `/api/jobs`。调用方必须拥有该产品线令牌。业务系统还需自行验证用户与任务的访问权。
|
|
28
|
+
|
|
29
|
+
## 两种业务调用
|
|
30
|
+
|
|
31
|
+
`job.json`:
|
|
32
|
+
|
|
33
|
+
```json
|
|
34
|
+
{
|
|
35
|
+
"title": "生成周报",
|
|
36
|
+
"tasks": [{"key": "report", "title": "生成周报", "prompt": "根据提供的数据生成 outputs/report.md,说明来源和限制。", "browser": false}]
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
# 接受后立即返回 IDs,不后台轮询
|
|
42
|
+
npx -y @spzxg/cli-skill@0.1.0 dispatch --input job.json
|
|
43
|
+
# 接受后等待,最多 60 秒
|
|
44
|
+
npx -y @spzxg/cli-skill@0.1.0 dispatch --input job.json --wait --timeout-seconds 60
|
|
45
|
+
# 延续已有任务的等待,不新建任务
|
|
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>
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
也支持 `--input -` 从 stdin 读取 JSON。`--browser true|false` 覆盖整个提交中的子任务;省略时保留每个 `tasks[].browser`,缺省 false。true 由现有服务在执行节点准备 ego 浏览器,本机不会启动浏览器。
|
|
51
|
+
|
|
52
|
+
多步骤共享一个工作区时,用 `tasks[].key` 与 `depends_on` 表达依赖;不同任务需要独立工作区时分别提交 Job。保留业务传入的 `business_id` 方便结果对应;新建 Job 接口不因此具备幂等性。`max_concurrent_tasks` 可选 1–20,实际调度与资源隔离继续由服务控制。
|
|
53
|
+
|
|
54
|
+
## 等待结果的含义
|
|
55
|
+
|
|
56
|
+
默认一次性 Job:等待 Job 终态,返回 `job.tasks` 中的状态、Token、错误及 `workspace` 产物位置。查询接口没有最终正文,也不自动下载文件;`succeeded` 不保证 `workspace.merged`,合并状态以该字段为准。
|
|
57
|
+
|
|
58
|
+
单个 Agent 需要返回正文时,使用对话模式:
|
|
59
|
+
|
|
60
|
+
```json
|
|
61
|
+
{
|
|
62
|
+
"title": "整理网页要点",
|
|
63
|
+
"mode": "conversation",
|
|
64
|
+
"tasks": [{"title": "整理网页要点", "prompt": "使用 ego 浏览器访问 https://example.com,返回主要内容和来源链接。", "browser": true}]
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`dispatch --wait` 自动等待创建响应中的初始 `turn.turn_id`,返回 `reply`。已有对话用 `wait <job_id> --turn-id <turn_id>`。对话轮次完成后 Job 保持打开,客户端不会自动关闭。对话模式只支持一个任务,不能带 `depends_on`、`done_when`、`browser_learn`。
|
|
69
|
+
|
|
70
|
+
结果结构:
|
|
71
|
+
|
|
72
|
+
```json
|
|
73
|
+
{"job_id":"job_...","status":"running","outcome":"timeout","completed":false,"timed_out":true,"result_kind":"job","job":{"id":"job_...","status":"running","tasks":[]}}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`outcome` 为 `succeeded`、`failed`、`cancelled`、`needs_input` 或 `timeout`。`status` 保留被等待对象的实际状态。`needs_input` 表示 API 观察到等待人工输入或本轮以问题结束;需要在现有中枢/cli-ui 界面继续,不提供浏览器接管或安全输入接口。旧服务若不提供输入状态,只能在等待预算内继续查询,不能保证提前发现所有阻塞。
|
|
77
|
+
|
|
78
|
+
默认等待预算 60 秒,最大 3600 秒;`--poll-interval-seconds` 默认 3 秒、最大 60 秒。等待时间包括排队,与子任务 `timeout_seconds` 的运行超时独立。到期仅停止本地等待,远端任务继续。MCP 客户端自身超时也可能更短,长任务建议先派发再按 ID 等待,或用现有 API 的业务回调。
|
|
79
|
+
|
|
80
|
+
CLI stdout 是 JSON;请求错误在 stderr。退出码:0 接受/成功,1 请求错误/任务失败,2 等待超时,3 取消,4 需要输入。
|
|
81
|
+
|
|
82
|
+
## 后端 JavaScript / TypeScript
|
|
83
|
+
|
|
84
|
+
```js
|
|
85
|
+
import { createClientFromEnv } from '@spzxg/cli-skill';
|
|
86
|
+
const center = createClientFromEnv();
|
|
87
|
+
const job = { title: '业务任务', tasks: [{ title: '执行', prompt: '完成工作并保存 outputs/result.md' }] };
|
|
88
|
+
const receipt = await center.dispatch(job, { browser: false });
|
|
89
|
+
const result = await center.waitForJob(receipt.job_id, { timeout_seconds: 60 });
|
|
90
|
+
// 或 await center.dispatchAndWait(job, { browser: true, timeout_seconds: 60 });
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
导出 `createClient({baseUrl, token, request_timeout_seconds?})`、`createClientFromEnv()`、`validateJob()`、`CenterApiError`,附 TypeScript 声明。支持 `AbortSignal`,请求默认 30 秒超时、不跟随重定向、不自动重试 POST。查询失败会携带已知 `job_id`;提交响应不确定时 `uncertain: true`,须先在中枢对账,不能直接重建任务。客户端校验常用字段、依赖图和会被服务忽略的错误模式,细节校验仍以现有服务为准。
|
|
94
|
+
|
|
95
|
+
需要回调时原样传 `callback: {url, code}`。业务消费方应核对 Bearer code,并按 API 的事件标识/版本去重。令牌和 callback code 仅由业务配置提供;不要提交到代码仓库或打印请求体。
|
|
96
|
+
|
|
97
|
+
本包未提供任务调度、Agent 执行、浏览器安装、界面组件、自动重试新任务或产物下载。前端组件使用 `@spzxg/cli-ui`;MCP 接入使用 `@spzxg/cli-mcp`。
|
package/bin/cli-skill.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { createClientFromEnv } from '../src/client.js';
|
|
5
|
+
import { installSkill } from '../src/install.js';
|
|
6
|
+
|
|
7
|
+
const help = `CLI Task Center · @spzxg/cli-skill 0.1.0
|
|
8
|
+
|
|
9
|
+
Install an agent skill:
|
|
10
|
+
cli-skill install [--agent codex|claude|all] [--dir <skills-directory>] [--force]
|
|
11
|
+
|
|
12
|
+
Use the existing Center HTTP API:
|
|
13
|
+
cli-skill dispatch --input <job.json|-> [--browser true|false] [--wait]
|
|
14
|
+
cli-skill get <job_id>
|
|
15
|
+
cli-skill wait <job_id> [--turn-id <turn_id>]
|
|
16
|
+
Wait options: --timeout-seconds <60> --poll-interval-seconds <3>
|
|
17
|
+
|
|
18
|
+
API commands require CLI_CENTER_BASE_URL and CLI_CENTER_TOKEN (product-line token).
|
|
19
|
+
Dispatch returns the API receipt. --wait returns a bounded wait result as JSON.
|
|
20
|
+
Browser true requests ego on the execution node. No local browser is launched.
|
|
21
|
+
Timeout leaves remote work running; use wait with the same IDs. Never resubmit blindly.
|
|
22
|
+
Exit: 0 success/accepted, 1 error/failed, 2 waiting timeout, 3 cancelled, 4 needs input.
|
|
23
|
+
`;
|
|
24
|
+
const write = value => process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
|
25
|
+
try {
|
|
26
|
+
const { values, positionals } = parseArgs({ allowPositionals: true, strict: true, options: {
|
|
27
|
+
input: { type: 'string' }, browser: { type: 'string' }, wait: { type: 'boolean' },
|
|
28
|
+
agent: { type: 'string' }, dir: { type: 'string' }, force: { type: 'boolean' },
|
|
29
|
+
'timeout-seconds': { type: 'string' }, 'poll-interval-seconds': { type: 'string' },
|
|
30
|
+
'turn-id': { type: 'string' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' },
|
|
31
|
+
} });
|
|
32
|
+
if (values.version) { process.stdout.write('0.1.0\n'); }
|
|
33
|
+
else if (values.help || !positionals.length) { process.stdout.write(help); }
|
|
34
|
+
else {
|
|
35
|
+
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');
|
|
37
|
+
const allowed = {
|
|
38
|
+
install: ['agent', 'dir', 'force'], dispatch: ['input', 'browser', 'wait', 'timeout-seconds', 'poll-interval-seconds'],
|
|
39
|
+
get: [], wait: ['turn-id', 'timeout-seconds', 'poll-interval-seconds'],
|
|
40
|
+
}[command];
|
|
41
|
+
for (const key of Object.keys(values)) if (!allowed.includes(key)) throw new TypeError(`--${key} is not valid for ${command}`);
|
|
42
|
+
if (command === 'install') {
|
|
43
|
+
if (id) throw new TypeError('install does not accept a positional argument');
|
|
44
|
+
write(await installSkill({ agent: values.agent, dir: values.dir, force: values.force }));
|
|
45
|
+
} else {
|
|
46
|
+
const opts = {};
|
|
47
|
+
for (const [flag, key] of [['timeout-seconds', 'timeout_seconds'], ['poll-interval-seconds', 'poll_interval_seconds']]) if (values[flag] !== undefined) opts[key] = Number(values[flag]);
|
|
48
|
+
if (values['turn-id'] !== undefined) opts.turn_id = values['turn-id'];
|
|
49
|
+
if (values.browser !== undefined) {
|
|
50
|
+
if (!['true', 'false'].includes(values.browser)) throw new TypeError('--browser must be true or false');
|
|
51
|
+
opts.browser = values.browser === 'true';
|
|
52
|
+
}
|
|
53
|
+
const client = createClientFromEnv();
|
|
54
|
+
let result;
|
|
55
|
+
if (command === 'dispatch') {
|
|
56
|
+
if (id || !values.input) throw new TypeError('dispatch requires --input <job.json|->');
|
|
57
|
+
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);
|
|
62
|
+
result = await (values.wait ? client.dispatchAndWait(job, opts) : client.dispatch(job, opts));
|
|
63
|
+
} else {
|
|
64
|
+
if (!id) throw new TypeError(`${command} requires a job_id`);
|
|
65
|
+
result = await (command === 'get' ? client.getJob(id) : client.waitForJob(id, opts));
|
|
66
|
+
}
|
|
67
|
+
write(result);
|
|
68
|
+
if (result.outcome) process.exitCode = ({ succeeded: 0, failed: 1, timeout: 2, cancelled: 3, needs_input: 4 })[result.outcome];
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
} catch (error) {
|
|
72
|
+
process.stderr.write(`${JSON.stringify({ error: error.name, message: error.message, ...(error.status ? { status: error.status } : {}), ...(error.code ? { code: error.code } : {}), ...(error.job_id ? { job_id: error.job_id } : {}), ...(error.receipt ? { receipt: error.receipt } : {}), ...(error.uncertain ? { uncertain: true } : {}) })}\n`);
|
|
73
|
+
process.exitCode = 1;
|
|
74
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spzxg/cli-skill",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
}
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
"type": "module",
|
|
6
|
+
"engines": { "node": ">=22" },
|
|
7
|
+
"bin": { "cli-skill": "./bin/cli-skill.js" },
|
|
8
|
+
"exports": { ".": { "types": "./src/client.d.ts", "default": "./src/client.js" } },
|
|
9
|
+
"types": "./src/client.d.ts",
|
|
10
|
+
"files": ["bin", "src", "skills", "README.md", "LICENSE"],
|
|
11
|
+
"scripts": {
|
|
12
|
+
"test": "node --test test/*.test.js",
|
|
13
|
+
"check": "node --check bin/cli-skill.js && node --check src/client.js && node --check src/install.js",
|
|
14
|
+
"prepublishOnly": "npm run check && npm test"
|
|
15
|
+
},
|
|
16
|
+
"publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" },
|
|
17
|
+
"keywords": ["cli-task-center", "skill", "codex", "claude-code", "ego-browser", "task-orchestration"],
|
|
18
|
+
"license": "MIT"
|
|
19
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
---
|
|
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.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# CLI Task Center
|
|
7
|
+
|
|
8
|
+
Use this skill when the user wants work executed by their configured Center and its remote CLI agents. It wraps the existing API; it does not install a Center, modify scheduling, or run the task locally.
|
|
9
|
+
|
|
10
|
+
## Configure once
|
|
11
|
+
|
|
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
|
+
|
|
14
|
+
Use `npx -y @spzxg/cli-skill@0.1.0` followed by the command below. A global installation also provides `cli-skill`.
|
|
15
|
+
|
|
16
|
+
## Choose the user's completion contract
|
|
17
|
+
|
|
18
|
+
- **Dispatch and leave:** `cli-skill dispatch --input job.json`. Return the API's `job_id`, `task_ids`, and initial `status`, then stop. Submission means accepted/queued, not completed. Do not poll or come back later unless the user asked for a callback or follow-up.
|
|
19
|
+
- **Dispatch and wait:** `cli-skill dispatch --input job.json --wait --timeout-seconds 60`. Return the wait result. The client wait budget is separate from each task's `timeout_seconds` and includes queue time.
|
|
20
|
+
- **Resume waiting for an existing job:** `cli-skill wait <job_id> --timeout-seconds 60`. For a conversation, also provide `--turn-id <turn_id>` from the creation receipt. Use `cli-skill get <job_id>` for a snapshot.
|
|
21
|
+
|
|
22
|
+
For normal CLI work, omit `mode` and use one or more `tasks`. The API reports final job/task state, usage, and workspace references; its Job query does not include a final reply or download artifact files. Do not invent a report body from `status: succeeded`. `workspace.merged` separately indicates whether a task's output branch merged.
|
|
23
|
+
|
|
24
|
+
If the user needs a text reply from a single remote agent, use `mode: "conversation"` and exactly one task. `dispatch --wait` waits for the **initial turn**, whose ID is returned in `receipt.turn.turn_id`, and returns its `reply`. A conversation Job remains open/idle after a turn completes. Do not wait for the conversation Job to become terminal or close it automatically. Conversation creation cannot include `depends_on`, `done_when`, or `browser_learn`.
|
|
25
|
+
|
|
26
|
+
## Plan useful task boundaries
|
|
27
|
+
|
|
28
|
+
Translate the request into concrete prompts with inputs, intended outputs, acceptance criteria, and output paths. Use a single task for a single work unit; do not split work mechanically. For related steps sharing one workspace, submit one Job with stable task `key` values and `depends_on` for real dependencies. The Center resolves their execution. Independent jobs needing separate workspaces require separate submissions.
|
|
29
|
+
|
|
30
|
+
```json
|
|
31
|
+
{
|
|
32
|
+
"title": "生成业务数据分析报告",
|
|
33
|
+
"workspace": { "context": "输入数据在业务提供的来源中;报告保存到 outputs。" },
|
|
34
|
+
"tasks": [
|
|
35
|
+
{ "key": "analyze", "title": "分析数据", "prompt": "核对输入并分析,保存 outputs/analysis.json。", "browser": false },
|
|
36
|
+
{ "key": "report", "title": "形成报告", "depends_on": ["analyze"], "prompt": "读取 outputs/analysis.json,生成 outputs/report.md,说明证据和限制。", "browser": false }
|
|
37
|
+
]
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
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
|
+
|
|
43
|
+
## Browser capability
|
|
44
|
+
|
|
45
|
+
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.
|
|
46
|
+
|
|
47
|
+
When a website requires login, verification, or user input, report `needs_input` and the returned job/task references so the user can continue in the existing Center/cli-ui interface. This package does not implement browser viewing, browser control, or secure credential input. Do not ask for passwords in task prompts.
|
|
48
|
+
|
|
49
|
+
## Interpret the response without resubmitting
|
|
50
|
+
|
|
51
|
+
- `outcome: succeeded|failed|cancelled` and `completed: true`: the awaited object reached a terminal state. Preserve failure details and artifact references from the API.
|
|
52
|
+
- `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
|
+
- `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.
|
|
55
|
+
|
|
56
|
+
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
|
+
|
|
58
|
+
For unattended dispatch with notification, the existing API supports `callback: { "url": "https://business.example/callback", "code": "..." }`. Obtain callback configuration from the business system; do not invent a destination. The service sends Bearer-authenticated notifications and may retry delivery, so the business consumer must handle duplicates. Callback codes belong only in protected request input, not in published examples or logs.
|
package/src/client.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export interface Callback { url: string; code: string }
|
|
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 TaskInput {
|
|
4
|
+
title: string; prompt: string; key?: string; business_id?: string; agent?: string;
|
|
5
|
+
depends_on?: string[]; done_when?: DoneWhen; timeout_seconds?: number; browser?: boolean;
|
|
6
|
+
browser_playbook?: string; browser_pacing?: unknown; browser_learn?: { callback: Callback };
|
|
7
|
+
callback?: Callback; workspace?: Record<string, unknown>;
|
|
8
|
+
}
|
|
9
|
+
export interface JobInput {
|
|
10
|
+
title: string; tasks: TaskInput[]; mode?: 'conversation'; max_concurrent_tasks?: number;
|
|
11
|
+
workspace?: { version?: 1; name?: string; context?: string; branch?: string }; callback?: Callback;
|
|
12
|
+
}
|
|
13
|
+
export interface DispatchReceipt {
|
|
14
|
+
id?: string; job_id: string; status: string; task_ids?: string[]; tasks?: string[];
|
|
15
|
+
task_refs?: Array<{task_id: string; task_key: string | null; business_id: string | null; seq: number}>;
|
|
16
|
+
turn?: TurnView; [key: string]: unknown;
|
|
17
|
+
}
|
|
18
|
+
export interface TurnView { turn_id: string; task_id: string; status: string; reply?: string | null; asked?: boolean; merged_into_turn_id?: string | null; [key: string]: unknown }
|
|
19
|
+
export interface JobView {
|
|
20
|
+
id: string; status: string; mode?: 'conversation'; tasks: Array<{id: string; status: string; awaiting_input?: boolean | null; [key: string]: unknown}>;
|
|
21
|
+
conversation?: { conversations?: Array<{task_id: string; awaiting_input?: boolean | null; [key: string]: unknown}>; [key: string]: unknown };
|
|
22
|
+
[key: string]: unknown;
|
|
23
|
+
}
|
|
24
|
+
export interface WaitOptions { timeout_seconds?: number; poll_interval_seconds?: number; turn_id?: string; signal?: AbortSignal }
|
|
25
|
+
export interface DispatchOptions { browser?: boolean; signal?: AbortSignal }
|
|
26
|
+
export interface WaitResult {
|
|
27
|
+
job_id: string; status: string; outcome: 'succeeded' | 'failed' | 'cancelled' | 'timeout' | 'needs_input';
|
|
28
|
+
completed: boolean; timed_out: boolean; result_kind: 'job' | 'turn'; job: JobView | null;
|
|
29
|
+
turn?: TurnView; reply?: string | null; receipt?: DispatchReceipt;
|
|
30
|
+
}
|
|
31
|
+
export interface CenterClient {
|
|
32
|
+
dispatch(job: JobInput, options?: DispatchOptions): Promise<DispatchReceipt>;
|
|
33
|
+
dispatchAndWait(job: JobInput, options?: Omit<WaitOptions, 'turn_id'> & DispatchOptions): Promise<WaitResult>;
|
|
34
|
+
getJob(id: string, options?: {signal?: AbortSignal}): Promise<JobView>;
|
|
35
|
+
getTurn(jobId: string, turnId: string, options?: {signal?: AbortSignal}): Promise<TurnView>;
|
|
36
|
+
waitForJob(id: string, options?: WaitOptions): Promise<WaitResult>;
|
|
37
|
+
}
|
|
38
|
+
export class CenterApiError extends Error { status?: number; code?: string; job_id?: string; uncertain: boolean; receipt?: DispatchReceipt }
|
|
39
|
+
export function validateJob(input: JobInput, options?: DispatchOptions): JobInput;
|
|
40
|
+
export function createClient(config: {baseUrl: string; token: string; request_timeout_seconds?: number; fetch?: typeof fetch}): CenterClient;
|
|
41
|
+
export function createClientFromEnv(env?: Record<string, string | undefined>): CenterClient;
|
package/src/client.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
|
+
|
|
3
|
+
const terminal = new Set(['succeeded', 'failed', 'cancelled']);
|
|
4
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
5
|
+
const nonempty = value => typeof value === 'string' && value.trim().length > 0;
|
|
6
|
+
function requireValue(condition, message) { if (!condition) throw new TypeError(message); }
|
|
7
|
+
function range(value, min, max, name) {
|
|
8
|
+
requireValue(typeof value === 'number' && Number.isFinite(value) && value >= min && value <= max, `${name} must be between ${min} and ${max}`);
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
function callback(value) {
|
|
12
|
+
requireValue(object(value) && nonempty(value.code), 'callback requires url and code');
|
|
13
|
+
let url;
|
|
14
|
+
try { url = new URL(value.url); } catch { throw new TypeError('callback.url must be an HTTP(S) URL'); }
|
|
15
|
+
requireValue(['https:', 'http:'].includes(url.protocol), 'callback.url must use HTTP(S)');
|
|
16
|
+
}
|
|
17
|
+
function judge(value) {
|
|
18
|
+
requireValue(object(value) && ['http', 'git_diff', 'agent_confirm', 'all', 'manual'].includes(value.kind), 'Unsupported done_when.kind');
|
|
19
|
+
if (value.kind === 'all') {
|
|
20
|
+
requireValue(Array.isArray(value.rules) && value.rules.length > 0, 'done_when.all requires rules');
|
|
21
|
+
value.rules.forEach(judge);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Validate wrapper-sensitive fields; the Center remains the API authority. */
|
|
26
|
+
export function validateJob(input, options = {}) {
|
|
27
|
+
requireValue(object(input) && nonempty(input.title), 'job.title is required');
|
|
28
|
+
const allowed = new Set(['title', 'mode', 'tasks', 'workspace', 'callback', 'max_concurrent_tasks']);
|
|
29
|
+
for (const key of Object.keys(input)) requireValue(allowed.has(key), `Unsupported job field: ${key}`);
|
|
30
|
+
requireValue(input.mode === undefined || input.mode === 'conversation', 'Omit mode for a one-shot job, or use conversation');
|
|
31
|
+
requireValue(Array.isArray(input.tasks) && input.tasks.length > 0, 'job.tasks must be a nonempty array');
|
|
32
|
+
if (options.browser !== undefined) requireValue(typeof options.browser === 'boolean', 'browser must be a boolean');
|
|
33
|
+
if (input.callback !== undefined) callback(input.callback);
|
|
34
|
+
if (input.max_concurrent_tasks !== undefined) requireValue(Number.isInteger(input.max_concurrent_tasks) && input.max_concurrent_tasks >= 1 && input.max_concurrent_tasks <= 20, 'max_concurrent_tasks must be an integer from 1 to 20');
|
|
35
|
+
if (input.workspace !== undefined) {
|
|
36
|
+
requireValue(object(input.workspace), 'workspace must be an object');
|
|
37
|
+
for (const key of Object.keys(input.workspace)) requireValue(['version', 'name', 'context', 'branch'].includes(key), `Unsupported workspace field: ${key}`);
|
|
38
|
+
}
|
|
39
|
+
const keys = new Map();
|
|
40
|
+
const tasks = input.tasks.map((task, index) => {
|
|
41
|
+
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']);
|
|
43
|
+
for (const key of Object.keys(task)) requireValue(fields.has(key), `Unsupported task field: ${key}`);
|
|
44
|
+
if (task.key !== undefined) requireValue(nonempty(task.key), 'task.key must be nonempty');
|
|
45
|
+
const key = task.key ?? `__seq_${index}`;
|
|
46
|
+
requireValue(!keys.has(key), `Duplicate task key: ${key}`);
|
|
47
|
+
keys.set(key, task.depends_on ?? []);
|
|
48
|
+
if (task.depends_on !== undefined) requireValue(Array.isArray(task.depends_on) && task.depends_on.every(nonempty), 'depends_on must contain task keys');
|
|
49
|
+
if (task.done_when !== undefined) judge(task.done_when);
|
|
50
|
+
if (task.timeout_seconds !== undefined) requireValue(Number.isInteger(task.timeout_seconds) && task.timeout_seconds > 0, 'task.timeout_seconds must be a positive integer');
|
|
51
|
+
if (task.agent !== undefined) requireValue(nonempty(task.agent), 'task.agent must be nonempty');
|
|
52
|
+
if (task.business_id !== undefined) requireValue(nonempty(task.business_id), 'task.business_id must be nonempty');
|
|
53
|
+
if (task.callback !== undefined) callback(task.callback);
|
|
54
|
+
const browser = options.browser ?? task.browser ?? false;
|
|
55
|
+
requireValue(typeof browser === 'boolean', 'task.browser must be a boolean');
|
|
56
|
+
if (task.browser_playbook !== undefined || task.browser_pacing !== undefined || task.browser_learn !== undefined) requireValue(browser, 'Browser options require browser: true');
|
|
57
|
+
if (input.mode === 'conversation') {
|
|
58
|
+
requireValue(input.tasks.length === 1, 'conversation requires exactly one task');
|
|
59
|
+
requireValue(task.done_when === undefined && task.depends_on === undefined, 'conversation does not accept done_when or depends_on');
|
|
60
|
+
requireValue(task.browser_learn === undefined, 'conversation does not accept browser_learn');
|
|
61
|
+
}
|
|
62
|
+
return { ...task, browser };
|
|
63
|
+
});
|
|
64
|
+
const visiting = new Set();
|
|
65
|
+
const visited = new Set();
|
|
66
|
+
function visit(key) {
|
|
67
|
+
requireValue(!visiting.has(key), 'depends_on contains a cycle');
|
|
68
|
+
if (visited.has(key)) return;
|
|
69
|
+
requireValue(keys.has(key), `Unknown task dependency: ${key}`);
|
|
70
|
+
visiting.add(key);
|
|
71
|
+
for (const dep of keys.get(key)) visit(dep);
|
|
72
|
+
visiting.delete(key); visited.add(key);
|
|
73
|
+
}
|
|
74
|
+
for (const key of keys.keys()) visit(key);
|
|
75
|
+
return { ...input, tasks };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export class CenterApiError extends Error {
|
|
79
|
+
constructor(message, { status, code, job_id, uncertain = false } = {}) {
|
|
80
|
+
super(message);
|
|
81
|
+
this.name = 'CenterApiError'; this.status = status; this.code = code;
|
|
82
|
+
this.job_id = job_id; this.uncertain = uncertain;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function createClient({ baseUrl, token, request_timeout_seconds = 30, fetch: fetchImpl = globalThis.fetch } = {}) {
|
|
87
|
+
requireValue(nonempty(baseUrl), 'CLI_CENTER_BASE_URL is required');
|
|
88
|
+
const base = new URL(baseUrl);
|
|
89
|
+
requireValue(['http:', 'https:'].includes(base.protocol) && !base.username && !base.password && !base.search && !base.hash, 'baseUrl must be an HTTP(S) root or proxy URL without credentials/query/fragment');
|
|
90
|
+
requireValue(nonempty(token) && !/[\r\n]/.test(token), 'CLI_CENTER_TOKEN is required and must be a single line');
|
|
91
|
+
range(request_timeout_seconds, 0.001, 300, 'request_timeout_seconds');
|
|
92
|
+
const prefix = base.href.replace(/\/+$/, '');
|
|
93
|
+
async function request(path, { method = 'GET', body, signal } = {}) {
|
|
94
|
+
signal?.throwIfAborted();
|
|
95
|
+
const requestSignal = AbortSignal.any([AbortSignal.timeout(Math.ceil(request_timeout_seconds * 1000)), ...(signal ? [signal] : [])]);
|
|
96
|
+
let response;
|
|
97
|
+
try {
|
|
98
|
+
response = await fetchImpl(`${prefix}${path}`, {
|
|
99
|
+
method, redirect: 'error', signal: requestSignal,
|
|
100
|
+
headers: { authorization: `Bearer ${token}`, accept: 'application/json', ...(body ? { 'content-type': 'application/json' } : {}) },
|
|
101
|
+
...(body ? { body: JSON.stringify(body) } : {}),
|
|
102
|
+
});
|
|
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 });
|
|
104
|
+
return await response.json();
|
|
105
|
+
} catch (error) {
|
|
106
|
+
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' });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const idPath = id => { requireValue(nonempty(id) && id.length <= 128, 'A valid id is required'); return encodeURIComponent(id); };
|
|
112
|
+
function waitOptions(options) {
|
|
113
|
+
const seconds = range(options.timeout_seconds ?? 60, 0.001, 3600, 'timeout_seconds');
|
|
114
|
+
const poll = range(options.poll_interval_seconds ?? 3, 0.001, 60, 'poll_interval_seconds');
|
|
115
|
+
if (options.turn_id !== undefined) idPath(options.turn_id);
|
|
116
|
+
return { seconds, poll };
|
|
117
|
+
}
|
|
118
|
+
async function getJob(id, options = {}) { return request(`/api/jobs/${idPath(id)}`, options); }
|
|
119
|
+
async function getTurn(id, turnId, options = {}) { return request(`/api/jobs/${idPath(id)}/turns/${idPath(turnId)}`, options); }
|
|
120
|
+
async function dispatch(input, options = {}) {
|
|
121
|
+
const receipt = await request('/api/jobs', { method: 'POST', body: validateJob(input, options), signal: options.signal });
|
|
122
|
+
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
|
+
return receipt;
|
|
124
|
+
}
|
|
125
|
+
async function waitForJob(job_id, options = {}) {
|
|
126
|
+
idPath(job_id);
|
|
127
|
+
const { seconds, poll } = waitOptions(options);
|
|
128
|
+
options.signal?.throwIfAborted();
|
|
129
|
+
const deadline = AbortSignal.timeout(Math.ceil(seconds * 1000));
|
|
130
|
+
const signal = AbortSignal.any([deadline, ...(options.signal ? [options.signal] : [])]);
|
|
131
|
+
let job = null, turn, turnId = options.turn_id;
|
|
132
|
+
const mergedIds = new Set();
|
|
133
|
+
const result = outcome => ({ job_id, status: turn?.status ?? job?.status ?? 'unknown', outcome, completed: terminal.has(outcome), timed_out: outcome === 'timeout', result_kind: turnId ? 'turn' : 'job', job, ...(turn ? { turn, reply: turn.reply ?? null } : {}) });
|
|
134
|
+
try {
|
|
135
|
+
while (true) {
|
|
136
|
+
job = await getJob(job_id, { signal });
|
|
137
|
+
if (job.mode === 'conversation') requireValue(turnId, 'Conversation waits require turn_id from the dispatch receipt');
|
|
138
|
+
if (turnId) {
|
|
139
|
+
turn = await getTurn(job_id, turnId, { signal });
|
|
140
|
+
if (turn.status === 'merged') {
|
|
141
|
+
requireValue(nonempty(turn.merged_into_turn_id) && !mergedIds.has(turn.merged_into_turn_id), 'Invalid merged turn chain');
|
|
142
|
+
mergedIds.add(turnId); turnId = turn.merged_into_turn_id; continue;
|
|
143
|
+
}
|
|
144
|
+
if (turn.asked === true) return result('needs_input');
|
|
145
|
+
if (terminal.has(turn.status)) return result(turn.status);
|
|
146
|
+
const conversation = job.conversation?.conversations?.find(item => item.task_id === turn.task_id);
|
|
147
|
+
if (conversation?.awaiting_input === true) return result('needs_input');
|
|
148
|
+
if (terminal.has(job.status)) return result(job.status === 'succeeded' ? 'cancelled' : job.status);
|
|
149
|
+
} else {
|
|
150
|
+
if (terminal.has(job.status)) return result(job.status);
|
|
151
|
+
if (job.tasks?.some(task => task.awaiting_input === true)) return result('needs_input');
|
|
152
|
+
}
|
|
153
|
+
await delay(Math.ceil(poll * 1000), undefined, { signal });
|
|
154
|
+
}
|
|
155
|
+
} catch (error) {
|
|
156
|
+
if (options.signal?.aborted) throw options.signal.reason;
|
|
157
|
+
if (deadline.aborted) return result('timeout');
|
|
158
|
+
if (error instanceof CenterApiError) error.job_id = job_id;
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async function dispatchAndWait(input, options = {}) {
|
|
163
|
+
waitOptions(options); // Reject bad wait arguments before creating a remote job.
|
|
164
|
+
const receipt = await dispatch(input, options);
|
|
165
|
+
const jobId = receipt.job_id ?? receipt.id;
|
|
166
|
+
try {
|
|
167
|
+
const result = await waitForJob(jobId, { ...options, turn_id: receipt.turn?.turn_id });
|
|
168
|
+
return { ...result, receipt };
|
|
169
|
+
} catch (error) {
|
|
170
|
+
if (error && typeof error === 'object') { error.job_id = jobId; error.receipt = receipt; }
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return { dispatch, dispatchAndWait, getJob, getTurn, waitForJob };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function createClientFromEnv(env = process.env) {
|
|
178
|
+
return createClient({ baseUrl: env.CLI_CENTER_BASE_URL, token: env.CLI_CENTER_TOKEN });
|
|
179
|
+
}
|
package/src/install.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { cp, mkdir, lstat, rename, rm, mkdtemp } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const source = fileURLToPath(new URL('../skills/cli-task-center/', import.meta.url));
|
|
7
|
+
async function exists(path) { try { await lstat(path); return true; } catch (e) { if (e.code === 'ENOENT') return false; throw e; } }
|
|
8
|
+
|
|
9
|
+
/** Explicit install only; never runs in npm postinstall. */
|
|
10
|
+
export async function installSkill({ agent = 'codex', dir, force = false, home = homedir(), codexHome = process.env.CODEX_HOME } = {}) {
|
|
11
|
+
if (!['codex', 'claude', 'all'].includes(agent)) throw new TypeError('--agent must be codex, claude or all');
|
|
12
|
+
if (dir && agent === 'all') throw new TypeError('--dir cannot be combined with --agent all');
|
|
13
|
+
const roots = dir ? [resolve(dir)] : [
|
|
14
|
+
...(agent !== 'claude' ? [join(codexHome || join(home, '.codex'), 'skills')] : []),
|
|
15
|
+
...(agent !== 'codex' ? [join(home, '.claude', 'skills')] : []),
|
|
16
|
+
];
|
|
17
|
+
const targets = roots.map(root => join(root, 'cli-task-center'));
|
|
18
|
+
// Check all destinations before writing any of them.
|
|
19
|
+
for (const target of targets) {
|
|
20
|
+
if (!(await exists(target))) continue;
|
|
21
|
+
const stat = await lstat(target);
|
|
22
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Refusing to replace a non-directory skill destination: ${target}`);
|
|
23
|
+
if (!force) throw new Error(`Skill already exists: ${target}; use --force to replace this skill only`);
|
|
24
|
+
}
|
|
25
|
+
for (const target of targets) {
|
|
26
|
+
await mkdir(dirname(target), { recursive: true });
|
|
27
|
+
const staging = await mkdtemp(join(dirname(target), '.cli-task-center-'));
|
|
28
|
+
const staged = join(staging, 'skill');
|
|
29
|
+
const backup = join(staging, 'previous');
|
|
30
|
+
let backedUp = false;
|
|
31
|
+
try {
|
|
32
|
+
await cp(source, staged, { recursive: true });
|
|
33
|
+
if (await exists(target)) { await rename(target, backup); backedUp = true; }
|
|
34
|
+
try { await rename(staged, target); } catch (e) { if (backedUp) await rename(backup, target); throw e; }
|
|
35
|
+
} finally { await rm(staging, { recursive: true, force: true }); }
|
|
36
|
+
}
|
|
37
|
+
return { installed: targets };
|
|
38
|
+
}
|