@tencent-adp/portal-cli 0.0.4 → 0.0.6
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/dist/acp/agent.d.ts +34 -0
- package/dist/acp/agent.js +111 -0
- package/dist/acp/server.js +14 -1
- package/dist/acp/session.d.ts +14 -0
- package/dist/acp/turn.d.ts +4 -0
- package/dist/acp/turn.js +123 -36
- package/dist/auth/loadAuth.js +2 -1
- package/dist/bin.js +6 -1
- package/dist/cli/ask.d.ts +6 -2
- package/dist/cli/ask.js +16 -3
- package/dist/cli/chat.js +0 -8
- package/dist/dev.d.ts +3 -0
- package/dist/dev.js +10 -0
- package/dist/portal/callerTools.d.ts +22 -65
- package/dist/portal/callerTools.js +103 -11
- package/dist/portal/chat.d.ts +2 -8
- package/dist/portal/chat.js +9 -21
- package/dist/portal/client.d.ts +0 -9
- package/dist/portal/client.js +0 -11
- package/dist/portal/sse.js +0 -30
- package/dist/portal/sseLog.d.ts +1 -0
- package/dist/portal/sseLog.js +10 -0
- package/dist/portal/types.d.ts +6 -6
- package/dist/tools/local.d.ts +35 -2
- package/dist/tools/local.js +148 -61
- package/dist/tools/tasks.d.ts +47 -0
- package/dist/tools/tasks.js +127 -0
- package/package.json +1 -1
|
@@ -1,24 +1,38 @@
|
|
|
1
|
-
|
|
2
|
-
'当前执行环境是调用方启动时所在的工作目录,命令和文件都在这台机器上,不在 Portal 沙箱里。',
|
|
3
|
-
'用户说当前项目、当前文件夹,指的都是这个执行环境。',
|
|
4
|
-
'在当前执行环境里,跑命令用 exec,读文件用 read,改文件用 edit。',
|
|
5
|
-
'改已有文件前先 read。edit 按原文逐字替换;要插入时把插入点前后的原文放进 old_string,',
|
|
6
|
-
'new_string 保留这段原文并加上新内容。new_string 为空是删除。',
|
|
7
|
-
'project_storage 只放用户要下载的最终结果,不要用它读写当前执行环境里的代码。',
|
|
8
|
-
].join('');
|
|
1
|
+
import { EXEC_YIELD_S, TASK_WAIT_S } from '../tools/local.js';
|
|
9
2
|
const READ_LINE_LIMIT = 2000;
|
|
10
|
-
|
|
3
|
+
const localExecTools = [
|
|
11
4
|
{
|
|
12
5
|
Name: 'exec',
|
|
13
|
-
Description:
|
|
6
|
+
Description: `在本地 bash 里执行一条命令,返回 stdout、stderr 和退出码。命令在 yield_time_s(秒,默认 ${EXEC_YIELD_S})内结束就直接返回结果;超过则转入后台并返回 task id。`,
|
|
14
7
|
InputSchema: {
|
|
15
8
|
type: 'object',
|
|
16
9
|
properties: {
|
|
17
10
|
command: { type: 'string', description: '要执行的 shell 命令' },
|
|
11
|
+
yield_time_s: {
|
|
12
|
+
type: 'number',
|
|
13
|
+
description: `等待多久后转后台,秒,默认 ${EXEC_YIELD_S}。`,
|
|
14
|
+
default: EXEC_YIELD_S,
|
|
15
|
+
},
|
|
18
16
|
},
|
|
19
17
|
required: ['command'],
|
|
20
18
|
},
|
|
21
19
|
},
|
|
20
|
+
{
|
|
21
|
+
Name: 'task_status',
|
|
22
|
+
Description: `查看后台任务(exec 转后台后返回的 task id)的状态、退出码,以及自上次查看以来的新输出。会先等 wait_time_s(秒,默认 ${TASK_WAIT_S})。不写入 stdin。`,
|
|
23
|
+
InputSchema: {
|
|
24
|
+
type: 'object',
|
|
25
|
+
properties: {
|
|
26
|
+
task_id: { type: 'string', description: 'exec 返回的 task id' },
|
|
27
|
+
wait_time_s: {
|
|
28
|
+
type: 'number',
|
|
29
|
+
description: `最多等多久,秒,默认 ${TASK_WAIT_S}。`,
|
|
30
|
+
default: TASK_WAIT_S,
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
required: ['task_id'],
|
|
34
|
+
},
|
|
35
|
+
},
|
|
22
36
|
{
|
|
23
37
|
Name: 'read',
|
|
24
38
|
Description: `读取本地 UTF-8 文本文件。offset 从 1 开始,limit 最多 ${READ_LINE_LIMIT} 行。`,
|
|
@@ -34,7 +48,7 @@ export const CALLER_TOOLS = [
|
|
|
34
48
|
},
|
|
35
49
|
{
|
|
36
50
|
Name: 'edit',
|
|
37
|
-
Description: '
|
|
51
|
+
Description: '按原文逐字替换一个已有的 UTF-8 文本文件里的内容。',
|
|
38
52
|
InputSchema: {
|
|
39
53
|
type: 'object',
|
|
40
54
|
properties: {
|
|
@@ -47,4 +61,82 @@ export const CALLER_TOOLS = [
|
|
|
47
61
|
},
|
|
48
62
|
},
|
|
49
63
|
];
|
|
64
|
+
const askUserTools = [
|
|
65
|
+
{
|
|
66
|
+
Name: 'ask_user',
|
|
67
|
+
Description: '向用户提一个必须由本人回答的问题(澄清或选项选择)。调用后本轮挂起,用户的答案作为这次调用的结果返回。',
|
|
68
|
+
InputSchema: {
|
|
69
|
+
type: 'object',
|
|
70
|
+
properties: {
|
|
71
|
+
questions: {
|
|
72
|
+
type: 'array',
|
|
73
|
+
description: '要问用户的问题(1–4 题)。',
|
|
74
|
+
minItems: 1,
|
|
75
|
+
maxItems: 4,
|
|
76
|
+
items: {
|
|
77
|
+
type: 'object',
|
|
78
|
+
properties: {
|
|
79
|
+
header: { type: 'string', description: '可选,题目上方的小标题,不要重复问题文本' },
|
|
80
|
+
question: { type: 'string', description: '要展示给用户的问题' },
|
|
81
|
+
options: {
|
|
82
|
+
type: 'array',
|
|
83
|
+
description: '供用户选择的选项(2–4 个)。',
|
|
84
|
+
minItems: 2,
|
|
85
|
+
maxItems: 4,
|
|
86
|
+
items: {
|
|
87
|
+
type: 'object',
|
|
88
|
+
properties: {
|
|
89
|
+
label: { type: 'string', description: '选项文案' },
|
|
90
|
+
description: { type: 'string', description: '可选,选项说明' },
|
|
91
|
+
},
|
|
92
|
+
required: ['label'],
|
|
93
|
+
additionalProperties: false,
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
multiple: { type: 'boolean', description: '是否可多选' },
|
|
97
|
+
},
|
|
98
|
+
required: ['question', 'options'],
|
|
99
|
+
additionalProperties: false,
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
required: ['questions'],
|
|
104
|
+
additionalProperties: false,
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
];
|
|
108
|
+
export const CALLER_TOOL_GROUPS = [
|
|
109
|
+
{
|
|
110
|
+
id: 'local_exec',
|
|
111
|
+
tools: localExecTools,
|
|
112
|
+
guidance: [
|
|
113
|
+
'你在调用方启动时所在的工作目录里干活:命令和文件都在这台机器上,不在 Portal 沙箱里。',
|
|
114
|
+
'用户说当前项目、当前文件夹,指的都是这个执行环境。跑命令用 exec,读文件用 read,改文件用 edit。',
|
|
115
|
+
'改已有文件前先 read。edit 按原文逐字替换;要插入时把插入点前后的原文放进 old_string,new_string 保留这段原文并加上新内容。new_string 为空是删除。',
|
|
116
|
+
'exec 超过 yield_time_s 仍在运行不会被杀掉,而是返回 task id;用 task_status 查进度和新输出。task_status 自己会等,不要用 sleep 轮询。',
|
|
117
|
+
'project_storage 只放用户要下载的最终结果,不要用它读写当前执行环境里的代码。',
|
|
118
|
+
'用 git 提交时,在提交消息末尾空一行,再加一行 "Co-authored-by: portal-cli"。',
|
|
119
|
+
].join(''),
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
id: 'ask_user',
|
|
123
|
+
tools: askUserTools,
|
|
124
|
+
guidance: [
|
|
125
|
+
'需要用户输入或选择时用 ask_user 提问,不要只在回复正文里提问。',
|
|
126
|
+
'每轮 1–4 题,每题 2–4 个选项;用户仍可手输。',
|
|
127
|
+
'不要用 ask_user 请求工具批准;删改文件走工具批准。',
|
|
128
|
+
'用户拒绝回答不代表同意:必须知道答案就停下,否则可以继续。',
|
|
129
|
+
].join(''),
|
|
130
|
+
},
|
|
131
|
+
];
|
|
132
|
+
/** 启用所有组时要下发的工具。 */
|
|
133
|
+
export const CALLER_TOOLS = CALLER_TOOL_GROUPS.flatMap((group) => group.tools);
|
|
134
|
+
/** 把各组的 prompt 拼成一段,交给对话协议的 ToolGuidance。 */
|
|
135
|
+
export function composeCallerToolGuidance(groups = CALLER_TOOL_GROUPS) {
|
|
136
|
+
return groups
|
|
137
|
+
.map((group) => group.guidance.trim())
|
|
138
|
+
.filter(Boolean)
|
|
139
|
+
.join('\n\n');
|
|
140
|
+
}
|
|
141
|
+
export const CALLER_TOOL_GUIDANCE = composeCallerToolGuidance();
|
|
50
142
|
//# sourceMappingURL=callerTools.js.map
|
package/dist/portal/chat.d.ts
CHANGED
|
@@ -1,16 +1,10 @@
|
|
|
1
|
-
import type { ChatTurn, ContextUsage, ThoughtBlock, ToolCall,
|
|
2
|
-
export declare class QuestionDeclined extends Error {
|
|
3
|
-
}
|
|
1
|
+
import type { AskUserReply, ChatTurn, ContextUsage, ThoughtBlock, ToolCall, UserQuestionItem } from './types.js';
|
|
4
2
|
export declare function chatBody(sessionId: string, turn: ChatTurn): Record<string, unknown>;
|
|
5
3
|
export declare function runChat(input: {
|
|
6
4
|
message: string;
|
|
7
5
|
cwd: string;
|
|
8
6
|
openStream: (turn: ChatTurn) => Promise<Response>;
|
|
9
|
-
ask: (
|
|
10
|
-
replyQuestion: (question: UserQuestion, reply: {
|
|
11
|
-
answers?: string[][];
|
|
12
|
-
rejected?: boolean;
|
|
13
|
-
}) => Promise<Response>;
|
|
7
|
+
ask: (questions: UserQuestionItem[]) => Promise<AskUserReply>;
|
|
14
8
|
onText?: (text: string) => Promise<void>;
|
|
15
9
|
onTitle?: (title: string) => Promise<void>;
|
|
16
10
|
onThought?: (thought: ThoughtBlock) => Promise<void>;
|
package/dist/portal/chat.js
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { createLocalTools } from '../tools/local.js';
|
|
3
|
+
import { CALLER_TOOL_GUIDANCE, CALLER_TOOLS } from './callerTools.js';
|
|
4
4
|
import { readChatStream } from './sse.js';
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
// One per process: the CLI talks to one machine, so its background tasks live
|
|
6
|
+
// as long as the process does.
|
|
7
|
+
const defaultTools = createLocalTools();
|
|
7
8
|
export function chatBody(sessionId, turn) {
|
|
8
9
|
return {
|
|
9
10
|
RequestId: randomBytes(16).toString('hex'),
|
|
10
11
|
ConversationId: sessionId,
|
|
11
12
|
Contents: turn.contents,
|
|
12
13
|
Tools: CALLER_TOOLS,
|
|
13
|
-
ToolGuidance:
|
|
14
|
+
ToolGuidance: CALLER_TOOL_GUIDANCE,
|
|
14
15
|
Incremental: true,
|
|
15
16
|
Stream: 'enable',
|
|
16
17
|
...(turn.previousResponseId ? { PreviousResponseId: turn.previousResponseId } : {}),
|
|
@@ -40,10 +41,6 @@ export async function runChat(input) {
|
|
|
40
41
|
// Keep the latest reported window usage; a turn can span several streams
|
|
41
42
|
// when local tools run in between.
|
|
42
43
|
contextUsage = segment.contextUsage ?? contextUsage;
|
|
43
|
-
if (segment.question) {
|
|
44
|
-
response = replyToQuestion(input, segment.question);
|
|
45
|
-
continue;
|
|
46
|
-
}
|
|
47
44
|
if (segment.completed || segment.calls.length === 0) {
|
|
48
45
|
return { text, sessionTitle, ...(contextUsage ? { contextUsage } : {}) };
|
|
49
46
|
}
|
|
@@ -52,22 +49,13 @@ export async function runChat(input) {
|
|
|
52
49
|
contents.push({
|
|
53
50
|
Type: 'function_call_output',
|
|
54
51
|
CallId: call.callId,
|
|
55
|
-
Output: input.onTool
|
|
52
|
+
Output: input.onTool
|
|
53
|
+
? await input.onTool(call)
|
|
54
|
+
: await defaultTools.run(input.cwd, call, { ask: input.ask }),
|
|
56
55
|
});
|
|
57
56
|
}
|
|
58
57
|
previousResponseId = segment.recordId;
|
|
59
58
|
response = input.openStream({ contents, previousResponseId });
|
|
60
59
|
}
|
|
61
60
|
}
|
|
62
|
-
async function replyToQuestion(input, question) {
|
|
63
|
-
try {
|
|
64
|
-
const answers = await input.ask(question);
|
|
65
|
-
return input.replyQuestion(question, { answers });
|
|
66
|
-
}
|
|
67
|
-
catch (error) {
|
|
68
|
-
if (!(error instanceof QuestionDeclined))
|
|
69
|
-
throw error;
|
|
70
|
-
return input.replyQuestion(question, { rejected: true });
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
61
|
//# sourceMappingURL=chat.js.map
|
package/dist/portal/client.d.ts
CHANGED
|
@@ -5,15 +5,6 @@ export declare class PortalClient {
|
|
|
5
5
|
constructor(auth: PortalAuth);
|
|
6
6
|
getJson<T>(pathname: string): Promise<T>;
|
|
7
7
|
postJson<T>(pathname: string, body: unknown, headers?: Record<string, string>): Promise<T>;
|
|
8
|
-
replyQuestion(input: {
|
|
9
|
-
spaceId: string;
|
|
10
|
-
agentId: string;
|
|
11
|
-
interactionId: string;
|
|
12
|
-
expectedVersion: number;
|
|
13
|
-
answers?: string[][];
|
|
14
|
-
rejected?: boolean;
|
|
15
|
-
signal?: AbortSignal;
|
|
16
|
-
}): Promise<Response>;
|
|
17
8
|
streamChat(input: {
|
|
18
9
|
spaceId: string;
|
|
19
10
|
agentId: string;
|
package/dist/portal/client.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { randomBytes } from 'node:crypto';
|
|
2
1
|
import { portalHeaders } from './headers.js';
|
|
3
2
|
import { loggedSseBody, logSse } from './sseLog.js';
|
|
4
3
|
export class PortalClient {
|
|
@@ -29,16 +28,6 @@ export class PortalClient {
|
|
|
29
28
|
const payload = await response.json();
|
|
30
29
|
return payload.data ?? payload;
|
|
31
30
|
}
|
|
32
|
-
replyQuestion(input) {
|
|
33
|
-
return this.post(`/api/spaces/${encodeURIComponent(input.spaceId)}/agents/${encodeURIComponent(input.agentId)}/runtime/interactions/${encodeURIComponent(input.interactionId)}/actions`, {
|
|
34
|
-
actionType: 'sys.chat',
|
|
35
|
-
actionPayload: input.rejected ? { rejected: true } : { answers: input.answers ?? [] },
|
|
36
|
-
expectedVersion: input.expectedVersion,
|
|
37
|
-
}, {
|
|
38
|
-
Accept: 'text/event-stream',
|
|
39
|
-
'Idempotency-Key': randomBytes(16).toString('hex'),
|
|
40
|
-
}, input.signal);
|
|
41
|
-
}
|
|
42
31
|
streamChat(input) {
|
|
43
32
|
return this.post(`/api/spaces/${encodeURIComponent(input.spaceId)}/chat/stream`, input.body, {
|
|
44
33
|
Accept: 'text/event-stream',
|
package/dist/portal/sse.js
CHANGED
|
@@ -93,9 +93,6 @@ async function applyBlock(block, state) {
|
|
|
93
93
|
if (event !== 'message.added' && event !== 'message.done')
|
|
94
94
|
return;
|
|
95
95
|
const message = data.Message;
|
|
96
|
-
const question = readQuestion(message?.ExtraInfo?.RuntimeInteraction);
|
|
97
|
-
if (question)
|
|
98
|
-
segment.question = question;
|
|
99
96
|
if (event !== 'message.done')
|
|
100
97
|
return;
|
|
101
98
|
if (message?.Type === 'reply') {
|
|
@@ -180,33 +177,6 @@ async function recordThought(state, thought) {
|
|
|
180
177
|
await state.callbacks.onThought?.(thought);
|
|
181
178
|
return true;
|
|
182
179
|
}
|
|
183
|
-
function readQuestion(interaction) {
|
|
184
|
-
if (!interaction || interaction.kind !== 'question' || interaction.status !== 'pending')
|
|
185
|
-
return undefined;
|
|
186
|
-
const detail = interaction.question;
|
|
187
|
-
const interactionId = String(interaction.interactionId || '');
|
|
188
|
-
const version = typeof interaction.version === 'number'
|
|
189
|
-
? interaction.version
|
|
190
|
-
: detail?.version;
|
|
191
|
-
const questions = Array.isArray(detail?.questions)
|
|
192
|
-
? detail.questions.map(readQuestionItem)
|
|
193
|
-
: [];
|
|
194
|
-
if (!interactionId || typeof version !== 'number' || questions.length === 0)
|
|
195
|
-
return undefined;
|
|
196
|
-
return { interactionId, version, questions };
|
|
197
|
-
}
|
|
198
|
-
function readQuestionItem(value) {
|
|
199
|
-
const item = value;
|
|
200
|
-
return {
|
|
201
|
-
question: String(item.question ?? ''),
|
|
202
|
-
header: String(item.header ?? ''),
|
|
203
|
-
multiple: item.multiple === true,
|
|
204
|
-
options: (item.options ?? []).map((option) => ({
|
|
205
|
-
label: String(option.label ?? ''),
|
|
206
|
-
description: String(option.description ?? ''),
|
|
207
|
-
})),
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
180
|
function readCall(content, fallbackName) {
|
|
211
181
|
const raw = content.Arguments;
|
|
212
182
|
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
package/dist/portal/sseLog.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare function sseLogFile(): string;
|
|
2
|
+
export declare function sseLogEnabled(): boolean;
|
|
2
3
|
export declare function logSse(label: string, body: string): void;
|
|
3
4
|
export declare function loggedSseBody(label: string, body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;
|
|
4
5
|
//# sourceMappingURL=sseLog.d.ts.map
|
package/dist/portal/sseLog.js
CHANGED
|
@@ -1,18 +1,28 @@
|
|
|
1
1
|
import { appendFileSync, mkdirSync } from 'node:fs';
|
|
2
2
|
import { homedir } from 'node:os';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import { isDevMode } from '../dev.js';
|
|
4
5
|
export function sseLogFile() {
|
|
5
6
|
return process.env.PORTAL_SSE_LOG ?? path.join(homedir(), '.portal', 'logs', 'sse.log');
|
|
6
7
|
}
|
|
8
|
+
// Packaged runs stay quiet: the SSE log is only written for a --dev run, or
|
|
9
|
+
// when a caller explicitly points at a log file (tests, manual debugging).
|
|
10
|
+
export function sseLogEnabled() {
|
|
11
|
+
return Boolean(process.env.PORTAL_SSE_LOG) || isDevMode();
|
|
12
|
+
}
|
|
7
13
|
// Already-buffered bodies only. A live response is logged by loggedSseBody,
|
|
8
14
|
// on the same read as the parser, so logging never owns a second stream.
|
|
9
15
|
export function logSse(label, body) {
|
|
16
|
+
if (!sseLogEnabled())
|
|
17
|
+
return;
|
|
10
18
|
remember(sseLogFile(), `\n----- ${new Date().toISOString()} ${label}\n${body}`);
|
|
11
19
|
}
|
|
12
20
|
// One reader. Chunks are forwarded to the caller and, separately, appended to
|
|
13
21
|
// the log. A failed or partial log write is discarded: it must not reject the
|
|
14
22
|
// chat, and it must not leave a promise that can crash the process.
|
|
15
23
|
export function loggedSseBody(label, body) {
|
|
24
|
+
if (!sseLogEnabled())
|
|
25
|
+
return body;
|
|
16
26
|
const file = sseLogFile();
|
|
17
27
|
remember(file, `\n----- ${new Date().toISOString()} ${label}\n`);
|
|
18
28
|
const reader = body.getReader();
|
package/dist/portal/types.d.ts
CHANGED
|
@@ -18,11 +18,12 @@ export interface UserQuestionItem {
|
|
|
18
18
|
options: UserQuestionOption[];
|
|
19
19
|
multiple?: boolean;
|
|
20
20
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
21
|
+
/** What the user did with an ask_user call: answer it, or decline. */
|
|
22
|
+
export type AskUserReply = {
|
|
23
|
+
answers: string[][];
|
|
24
|
+
} | {
|
|
25
|
+
declined: true;
|
|
26
|
+
};
|
|
26
27
|
export type ChatContent = {
|
|
27
28
|
Type: 'text';
|
|
28
29
|
Text: string;
|
|
@@ -47,7 +48,6 @@ export interface StreamSegment {
|
|
|
47
48
|
completed: boolean;
|
|
48
49
|
errors: string[];
|
|
49
50
|
sessionTitle: string;
|
|
50
|
-
question?: UserQuestion;
|
|
51
51
|
contextUsage?: ContextUsage;
|
|
52
52
|
}
|
|
53
53
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/tools/local.d.ts
CHANGED
|
@@ -1,3 +1,36 @@
|
|
|
1
|
-
import type { ToolCall } from '../portal/types.js';
|
|
2
|
-
|
|
1
|
+
import type { AskUserReply, ToolCall, UserQuestionItem } from '../portal/types.js';
|
|
2
|
+
import { BackgroundTasks } from './tasks.js';
|
|
3
|
+
/** How long exec waits before handing the command over to the background, in seconds. */
|
|
4
|
+
export declare const EXEC_YIELD_S = 10;
|
|
5
|
+
/** How long task_status waits for the task to exit before reporting progress, in seconds. */
|
|
6
|
+
export declare const TASK_WAIT_S = 10;
|
|
7
|
+
export interface LocalToolHost {
|
|
8
|
+
/** Notified when a command that outlived exec's wait window exits. */
|
|
9
|
+
onTaskExit?: (snapshot: {
|
|
10
|
+
taskId: string;
|
|
11
|
+
exitCode: number | null;
|
|
12
|
+
output: string;
|
|
13
|
+
}) => void;
|
|
14
|
+
}
|
|
15
|
+
export declare const ASK_USER_TOOL_NAME = "ask_user";
|
|
16
|
+
export interface RunOptions {
|
|
17
|
+
/** The turn was cancelled: stop waiting, and stop the command. */
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
/** How long exec waits before handing the command over to the background, in seconds. */
|
|
20
|
+
yieldS?: number;
|
|
21
|
+
/** How the user is asked when the model calls ask_user. */
|
|
22
|
+
ask?: (questions: UserQuestionItem[]) => Promise<AskUserReply>;
|
|
23
|
+
}
|
|
24
|
+
/** What a tool reports back when the turn was cancelled while it ran. */
|
|
25
|
+
export declare const CANCELLED = "\u5DF2\u53D6\u6D88\uFF1A\u547D\u4EE4\u5DF2\u7EC8\u6B62\u3002";
|
|
26
|
+
/**
|
|
27
|
+
* Runs the tools the model calls against this machine.
|
|
28
|
+
*
|
|
29
|
+
* A command that outlives `yield_time_ms` is not killed: it keeps running and
|
|
30
|
+
* the caller is handed a task id, so a long build does not block the turn.
|
|
31
|
+
*/
|
|
32
|
+
export declare function createLocalTools(host?: LocalToolHost): {
|
|
33
|
+
tasks: BackgroundTasks;
|
|
34
|
+
run(cwd: string, call: ToolCall, options?: RunOptions): Promise<string>;
|
|
35
|
+
};
|
|
3
36
|
//# sourceMappingURL=local.d.ts.map
|
package/dist/tools/local.js
CHANGED
|
@@ -1,72 +1,159 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
2
1
|
import { readFileSync, writeFileSync } from 'node:fs';
|
|
3
2
|
import path from 'node:path';
|
|
3
|
+
import { BackgroundTasks } from './tasks.js';
|
|
4
|
+
/** How long exec waits before handing the command over to the background, in seconds. */
|
|
5
|
+
export const EXEC_YIELD_S = 10;
|
|
6
|
+
/** How long task_status waits for the task to exit before reporting progress, in seconds. */
|
|
7
|
+
export const TASK_WAIT_S = 10;
|
|
8
|
+
const MS_PER_S = 1000;
|
|
4
9
|
const READ_LINE_LIMIT = 2000;
|
|
5
|
-
const
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
return
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
child.stdout.on('data', (chunk) => { stdout += chunk; });
|
|
38
|
-
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
39
|
-
// A timeout aborts the signal and emits 'error'. Leaving that unhandled
|
|
40
|
-
// kills the ACP process, so the failure never goes back to the remote.
|
|
41
|
-
child.on('error', (error) => {
|
|
42
|
-
if (signal.aborted)
|
|
43
|
-
stopCommand(child);
|
|
44
|
-
finish(signal.aborted ? timeoutResult(stdout, stderr, timeoutMs) : error.message);
|
|
45
|
-
});
|
|
46
|
-
child.on('close', (code) => {
|
|
47
|
-
if (signal.aborted) {
|
|
48
|
-
finish(timeoutResult(stdout, stderr, timeoutMs));
|
|
49
|
-
return;
|
|
10
|
+
export const ASK_USER_TOOL_NAME = 'ask_user';
|
|
11
|
+
/** ask_user 的题量与选项上下限,与工具 schema 保持一致。 */
|
|
12
|
+
const ASK_USER_MIN_QUESTIONS = 1;
|
|
13
|
+
const ASK_USER_MAX_QUESTIONS = 4;
|
|
14
|
+
const ASK_USER_MIN_OPTIONS = 2;
|
|
15
|
+
const ASK_USER_MAX_OPTIONS = 4;
|
|
16
|
+
/** What a tool reports back when the turn was cancelled while it ran. */
|
|
17
|
+
export const CANCELLED = '已取消:命令已终止。';
|
|
18
|
+
/**
|
|
19
|
+
* Runs the tools the model calls against this machine.
|
|
20
|
+
*
|
|
21
|
+
* A command that outlives `yield_time_ms` is not killed: it keeps running and
|
|
22
|
+
* the caller is handed a task id, so a long build does not block the turn.
|
|
23
|
+
*/
|
|
24
|
+
export function createLocalTools(host = {}) {
|
|
25
|
+
const tasks = new BackgroundTasks();
|
|
26
|
+
return {
|
|
27
|
+
tasks,
|
|
28
|
+
async run(cwd, call, options = {}) {
|
|
29
|
+
try {
|
|
30
|
+
if (call.name === 'exec') {
|
|
31
|
+
return await runExec(cwd, call.arguments, tasks, host, options);
|
|
32
|
+
}
|
|
33
|
+
if (call.name === 'task_status')
|
|
34
|
+
return await readTaskOutput(call.arguments, tasks, options);
|
|
35
|
+
if (call.name === 'read')
|
|
36
|
+
return read(cwd, call.arguments);
|
|
37
|
+
if (call.name === 'edit')
|
|
38
|
+
return edit(cwd, call.arguments);
|
|
39
|
+
if (call.name === ASK_USER_TOOL_NAME)
|
|
40
|
+
return await runAskUser(call.arguments, options);
|
|
41
|
+
return `Tool ${call.name} is not available in this environment.`;
|
|
50
42
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
43
|
+
catch (error) {
|
|
44
|
+
return error instanceof Error ? error.message : String(error);
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Reads a window given in seconds and hands back milliseconds for the timers.
|
|
51
|
+
* Seconds carry fractions, so 0.5 is a valid window.
|
|
52
|
+
*/
|
|
53
|
+
function windowMs(args, key, fallbackS, allowZero) {
|
|
54
|
+
const raw = args[key];
|
|
55
|
+
const value = typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : raw;
|
|
56
|
+
const usable = typeof value === 'number' && Number.isFinite(value) && (allowZero ? value >= 0 : value > 0);
|
|
57
|
+
return Math.max(0, Math.round((usable ? value : fallbackS) * MS_PER_S));
|
|
58
|
+
}
|
|
59
|
+
async function runExec(cwd, args, tasks, host, options) {
|
|
60
|
+
const command = String(args.command ?? '');
|
|
61
|
+
const task = tasks.start(cwd, command, host.onTaskExit);
|
|
62
|
+
const window = windowMs(args, 'yield_time_s', options.yieldS ?? EXEC_YIELD_S, false);
|
|
63
|
+
const snapshot = await tasks.wait(task.id, window, options.signal);
|
|
64
|
+
// The command ended inside the window: its output is the answer.
|
|
65
|
+
if (snapshot && !snapshot.running)
|
|
66
|
+
return snapshot.output;
|
|
67
|
+
// The user stopped the turn. Nothing will be handed back to the model, so
|
|
68
|
+
// nobody could ever read the task later: take the command down with it.
|
|
69
|
+
if (options.signal?.aborted) {
|
|
70
|
+
tasks.stop(task.id);
|
|
71
|
+
return CANCELLED;
|
|
72
|
+
}
|
|
73
|
+
// Still running: hand over the id. Output so far comes along so an error that
|
|
74
|
+
// happened early is not lost while the command keeps going. This is the
|
|
75
|
+
// snapshot the window already read, so nothing is drained twice.
|
|
76
|
+
return [
|
|
77
|
+
`background task started: ${task.id}`,
|
|
78
|
+
'it is still running; check it with task_status(task_id="' + task.id + '")',
|
|
79
|
+
snapshot?.output ? `output so far:\n${snapshot.output}` : '',
|
|
80
|
+
].filter((part) => part.length > 0).join('\n');
|
|
54
81
|
}
|
|
55
|
-
function
|
|
56
|
-
const
|
|
57
|
-
const
|
|
58
|
-
|
|
82
|
+
async function readTaskOutput(args, tasks, options) {
|
|
83
|
+
const taskId = String(args.task_id ?? '');
|
|
84
|
+
const waitMs = options.signal?.aborted ? 0 : windowMs(args, 'wait_time_s', TASK_WAIT_S, true);
|
|
85
|
+
const snapshot = taskId ? await tasks.wait(taskId, waitMs, options.signal) : null;
|
|
86
|
+
if (!snapshot)
|
|
87
|
+
return `unknown task: ${taskId}`;
|
|
88
|
+
if (snapshot.running && options.signal?.aborted)
|
|
89
|
+
return `${taskId}: 已取消`;
|
|
90
|
+
const status = snapshot.running
|
|
91
|
+
? 'still running'
|
|
92
|
+
: `exited with code ${snapshot.exitCode ?? 'null'}`;
|
|
93
|
+
return [
|
|
94
|
+
`${taskId}: ${status}`,
|
|
95
|
+
snapshot.output,
|
|
96
|
+
].filter((part) => part.length > 0).join('\n');
|
|
59
97
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
98
|
+
/**
|
|
99
|
+
* ask_user 是一次前端工具调用:它不在这里算答案,只是把问题交给调用方,
|
|
100
|
+
* 再把用户的选择按工具结果的形状交回去。
|
|
101
|
+
*/
|
|
102
|
+
async function runAskUser(args, options) {
|
|
103
|
+
const questions = readUserQuestions(args.questions);
|
|
104
|
+
if (questions.length === 0) {
|
|
105
|
+
return `ask_user 需要 questions:${ASK_USER_MIN_QUESTIONS}–${ASK_USER_MAX_QUESTIONS} 题,每题 ${ASK_USER_MIN_OPTIONS}–${ASK_USER_MAX_OPTIONS} 个选项。没有向用户展示任何内容。`;
|
|
106
|
+
}
|
|
107
|
+
if (!options.ask) {
|
|
108
|
+
return '当前环境无法展示交互式提问。请改用正文直接提问。';
|
|
65
109
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
110
|
+
const reply = await options.ask(questions);
|
|
111
|
+
if ('declined' in reply) {
|
|
112
|
+
return JSON.stringify({
|
|
113
|
+
resultType: 'rejected',
|
|
114
|
+
questions,
|
|
115
|
+
answers: [],
|
|
116
|
+
message: '用户拒绝回答。不要把拒绝当成同意:必须知道答案就停下来,否则可以继续。',
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
return JSON.stringify({ resultType: 'answered', questions, answers: reply.answers });
|
|
120
|
+
}
|
|
121
|
+
/** Model output is untrusted: keep only questions that can actually be shown. */
|
|
122
|
+
function readUserQuestions(raw) {
|
|
123
|
+
if (!Array.isArray(raw))
|
|
124
|
+
return [];
|
|
125
|
+
const questions = [];
|
|
126
|
+
for (const entry of raw) {
|
|
127
|
+
if (!entry || typeof entry !== 'object')
|
|
128
|
+
continue;
|
|
129
|
+
const record = entry;
|
|
130
|
+
const question = typeof record.question === 'string' ? record.question.trim() : '';
|
|
131
|
+
const options = (Array.isArray(record.options) ? record.options : [])
|
|
132
|
+
.map((option) => {
|
|
133
|
+
if (!option || typeof option !== 'object')
|
|
134
|
+
return undefined;
|
|
135
|
+
const fields = option;
|
|
136
|
+
const label = typeof fields.label === 'string' ? fields.label.trim() : '';
|
|
137
|
+
if (!label)
|
|
138
|
+
return undefined;
|
|
139
|
+
const description = typeof fields.description === 'string' ? fields.description.trim() : '';
|
|
140
|
+
return { label, description };
|
|
141
|
+
})
|
|
142
|
+
.filter((option) => Boolean(option))
|
|
143
|
+
.slice(0, ASK_USER_MAX_OPTIONS);
|
|
144
|
+
if (!question || options.length === 0)
|
|
145
|
+
continue;
|
|
146
|
+
const header = typeof record.header === 'string' ? record.header.trim() : '';
|
|
147
|
+
questions.push({
|
|
148
|
+
question,
|
|
149
|
+
header,
|
|
150
|
+
options,
|
|
151
|
+
...(record.multiple === true ? { multiple: true } : {}),
|
|
152
|
+
});
|
|
153
|
+
if (questions.length >= ASK_USER_MAX_QUESTIONS)
|
|
154
|
+
break;
|
|
69
155
|
}
|
|
156
|
+
return questions;
|
|
70
157
|
}
|
|
71
158
|
function read(cwd, args) {
|
|
72
159
|
const filePath = String(args.file_path ?? args.path ?? '');
|