@tencent-adp/portal-cli 0.0.5 → 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/turn.js CHANGED
@@ -1,21 +1,13 @@
1
1
  import path from 'node:path';
2
2
  import { methods } from '@agentclientprotocol/sdk';
3
3
  import { rememberSession } from '../cli/sessions.js';
4
- import { chatBody, QuestionDeclined, runChat } from '../portal/chat.js';
4
+ import { chatBody, runChat } from '../portal/chat.js';
5
+ import { ASK_USER_TOOL_NAME } from '../tools/local.js';
5
6
  export async function runAcpTurn(input) {
6
7
  const result = await runChat({
7
8
  message: input.message,
8
9
  cwd: input.session.cwd,
9
- ask: (question) => askUser(input, question),
10
- replyQuestion: (question, reply) => input.client.replyQuestion({
11
- spaceId: input.spaceId,
12
- agentId: input.agentId,
13
- interactionId: question.interactionId,
14
- expectedVersion: question.version,
15
- answers: reply.answers,
16
- rejected: reply.rejected,
17
- signal: input.signal,
18
- }),
10
+ ask: (questions) => askUser(input, questions),
19
11
  onText: (text) => update(input, {
20
12
  sessionUpdate: 'agent_message_chunk',
21
13
  content: { type: 'text', text },
@@ -86,29 +78,105 @@ function unseenThoughtSuffix(input, thought) {
86
78
  input.session.sentThoughts.set(thought.id, thought.text);
87
79
  return suffix;
88
80
  }
89
- async function askUser(input, question) {
81
+ async function askUser(input, questions) {
90
82
  const answers = [];
91
- for (const [index, item] of question.questions.entries()) {
92
- const response = await input.acp.request(methods.client.session.requestPermission, {
93
- sessionId: input.session.id,
94
- toolCall: {
95
- toolCallId: `${question.interactionId}-${index}`,
96
- title: item.question || item.header || '需要你回答',
97
- kind: 'other',
98
- status: 'pending',
99
- rawInput: { question: item.question, options: item.options },
83
+ try {
84
+ for (const [index, item] of questions.entries()) {
85
+ const toolCallId = `${input.session.id}-ask-${index}`;
86
+ const title = item.question || item.header || '需要你回答';
87
+ // Multiple choice cannot be expressed as permission buttons: Zed renders
88
+ // every option as a single-click allow, so a user can never pick more than
89
+ // one. An elicitation form with an array field renders real checkboxes and
90
+ // only submits on an explicit accept.
91
+ answers.push(item.multiple
92
+ ? await askMultiSelect(input, toolCallId, title, item)
93
+ : await askSingleSelect(input, toolCallId, title, item));
94
+ }
95
+ return { answers };
96
+ }
97
+ catch (error) {
98
+ if (error instanceof QuestionDeclined)
99
+ return { declined: true };
100
+ throw error;
101
+ }
102
+ }
103
+ /** The user closed the question form without answering. */
104
+ class QuestionDeclined extends Error {
105
+ }
106
+ async function askMultiSelect(input, toolCallId, title, item) {
107
+ await update(input, {
108
+ sessionUpdate: 'tool_call',
109
+ toolCallId,
110
+ title,
111
+ kind: 'other',
112
+ status: 'pending',
113
+ rawInput: { question: item.question, options: item.options, multiple: true },
114
+ });
115
+ const response = await input.acp.request(methods.client.elicitation.create, {
116
+ mode: 'form',
117
+ sessionId: input.session.id,
118
+ toolCallId,
119
+ message: title,
120
+ requestedSchema: {
121
+ type: 'object',
122
+ properties: {
123
+ answer: {
124
+ type: 'array',
125
+ title,
126
+ items: {
127
+ anyOf: item.options.map((option) => ({
128
+ const: option.label,
129
+ title: option.description ? `${option.label} — ${option.description}` : option.label,
130
+ })),
131
+ },
132
+ minItems: 1,
133
+ },
100
134
  },
101
- options: permissionOptions(item),
102
- }, {
103
- cancellationSignal: input.signal,
104
- stopWaitingOnCancel: true,
105
- });
106
- if (response.outcome.outcome !== 'selected')
107
- throw new QuestionDeclined();
108
- const selected = item.options[Number(response.outcome.optionId)];
109
- answers.push([selected?.label ?? response.outcome.optionId]);
135
+ required: ['answer'],
136
+ },
137
+ }, {
138
+ cancellationSignal: input.signal,
139
+ stopWaitingOnCancel: true,
140
+ });
141
+ if (response.action !== 'accept') {
142
+ await completeQuestionToolCall(input, toolCallId, 'failed', '用户取消了提问');
143
+ throw new QuestionDeclined();
110
144
  }
111
- return answers;
145
+ const raw = response.content?.answer;
146
+ const selected = Array.isArray(raw)
147
+ ? raw.filter((value) => typeof value === 'string')
148
+ : [];
149
+ await completeQuestionToolCall(input, toolCallId, 'completed', selected.join(', '));
150
+ return selected;
151
+ }
152
+ async function askSingleSelect(input, toolCallId, title, item) {
153
+ const response = await input.acp.request(methods.client.session.requestPermission, {
154
+ sessionId: input.session.id,
155
+ toolCall: {
156
+ toolCallId,
157
+ title,
158
+ kind: 'other',
159
+ status: 'pending',
160
+ rawInput: { question: item.question, options: item.options },
161
+ },
162
+ options: permissionOptions(item),
163
+ }, {
164
+ cancellationSignal: input.signal,
165
+ stopWaitingOnCancel: true,
166
+ });
167
+ if (response.outcome.outcome !== 'selected')
168
+ throw new QuestionDeclined();
169
+ const selected = item.options[Number(response.outcome.optionId)];
170
+ return [selected?.label ?? response.outcome.optionId];
171
+ }
172
+ async function completeQuestionToolCall(input, toolCallId, status, text) {
173
+ await update(input, {
174
+ sessionUpdate: 'tool_call_update',
175
+ toolCallId,
176
+ status,
177
+ rawOutput: text,
178
+ content: [{ type: 'content', content: { type: 'text', text } }],
179
+ });
112
180
  }
113
181
  function permissionOptions(item) {
114
182
  return item.options.map((option, index) => ({
@@ -118,6 +186,14 @@ function permissionOptions(item) {
118
186
  }));
119
187
  }
120
188
  async function reportTool(input, call) {
189
+ // ask_user draws its own question form (permission buttons or an elicitation
190
+ // form); a generic tool call card on top of that would only be noise.
191
+ if (call.name === ASK_USER_TOOL_NAME) {
192
+ return input.tools.run(input.session.cwd, call, {
193
+ signal: input.signal,
194
+ ask: (questions) => askUser(input, questions),
195
+ });
196
+ }
121
197
  const filePath = typeof call.arguments.file_path === 'string' ? call.arguments.file_path : '';
122
198
  await update(input, {
123
199
  sessionUpdate: 'tool_call',
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } 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
  const TEMPLATE = {
5
6
  baseUrl: 'https://portal.adp.woa.com',
6
7
  apiKey: '',
@@ -12,7 +13,7 @@ export function authFile() {
12
13
  if (process.env.NODE_TEST_CONTEXT) {
13
14
  throw new Error('Refusing to use ~/.portal/auth.json during tests. Set PORTAL_AUTH_FILE.');
14
15
  }
15
- return path.join(homedir(), '.portal', 'auth.json');
16
+ return path.join(homedir(), '.portal', isDevMode() ? 'auth.dev.json' : 'auth.json');
16
17
  }
17
18
  export function readAuthFile() {
18
19
  const file = authFile();
package/dist/bin.js CHANGED
@@ -1,7 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { serveAcp } from './acp/server.js';
3
3
  import { chat } from './cli/chat.js';
4
- const args = process.argv.slice(2);
4
+ import { setDevMode } from './dev.js';
5
+ const raw = process.argv.slice(2);
6
+ // --dev can appear anywhere: it selects auth.dev.json and turns on the SSE log.
7
+ if (raw.includes('--dev'))
8
+ setDevMode(true);
9
+ const args = raw.filter((arg) => arg !== '--dev');
5
10
  if (args[0] === 'acp') {
6
11
  await serveAcp();
7
12
  }
package/dist/cli/ask.d.ts CHANGED
@@ -1,3 +1,7 @@
1
- import type { UserQuestion } from '../portal/types.js';
2
- export declare function askQuestions(question: UserQuestion): Promise<string[][]>;
1
+ import type { AskUserReply, UserQuestionItem } from '../portal/types.js';
2
+ /**
3
+ * Answers an ask_user call in the terminal. Closing stdin (Ctrl-D) counts as a
4
+ * decline rather than an answer, so the model is never handed a made-up one.
5
+ */
6
+ export declare function askQuestions(questions: UserQuestionItem[]): Promise<AskUserReply>;
3
7
  //# sourceMappingURL=ask.d.ts.map
package/dist/cli/ask.js CHANGED
@@ -1,17 +1,30 @@
1
1
  import { stdin, stdout } from 'node:process';
2
2
  import { createInterface } from 'node:readline/promises';
3
- export async function askQuestions(question) {
3
+ /**
4
+ * Answers an ask_user call in the terminal. Closing stdin (Ctrl-D) counts as a
5
+ * decline rather than an answer, so the model is never handed a made-up one.
6
+ */
7
+ export async function askQuestions(questions) {
4
8
  const rl = createInterface({ input: stdin, output: stdout });
5
9
  const answers = [];
6
10
  try {
7
- for (const item of question.questions) {
11
+ for (const item of questions) {
8
12
  answers.push(await askOne(rl, item));
9
13
  }
14
+ return { answers };
15
+ }
16
+ catch (error) {
17
+ if (isCancelled(error))
18
+ return { declined: true };
19
+ throw error;
10
20
  }
11
21
  finally {
12
22
  rl.close();
13
23
  }
14
- return answers;
24
+ }
25
+ /** readline reports Ctrl-D (and Ctrl-C while waiting) as an abort. */
26
+ function isCancelled(error) {
27
+ return error instanceof Error && (error.name === 'AbortError' || error.name === 'ExitPromptError');
15
28
  }
16
29
  async function askOne(rl, item) {
17
30
  if (item.header)
package/dist/cli/chat.js CHANGED
@@ -24,14 +24,6 @@ export async function chat(input) {
24
24
  message: input.message,
25
25
  cwd,
26
26
  ask: askQuestions,
27
- replyQuestion: (question, reply) => client.replyQuestion({
28
- spaceId: auth.spaceId,
29
- agentId: target.agentId,
30
- interactionId: question.interactionId,
31
- expectedVersion: question.version,
32
- answers: reply.answers,
33
- rejected: reply.rejected,
34
- }),
35
27
  openStream: (turn) => client.streamChat({
36
28
  spaceId: auth.spaceId,
37
29
  agentId: target.agentId,
package/dist/dev.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export declare function setDevMode(value: boolean): void;
2
+ export declare function isDevMode(): boolean;
3
+ //# sourceMappingURL=dev.d.ts.map
package/dist/dev.js ADDED
@@ -0,0 +1,10 @@
1
+ // Set by the CLI entry point when --dev is passed. A source-run session keeps
2
+ // its own auth file and writes the SSE log; a packaged run stays quiet.
3
+ let enabled = false;
4
+ export function setDevMode(value) {
5
+ enabled = value;
6
+ }
7
+ export function isDevMode() {
8
+ return enabled;
9
+ }
10
+ //# sourceMappingURL=dev.js.map
@@ -1,107 +1,25 @@
1
- export declare const TOOL_GUIDANCE: string;
2
- export declare const CALLER_TOOLS: ({
1
+ /** 前端工具(caller tool)声明,形状与运行时的 Tools 字段一致。 */
2
+ export interface CallerToolDefinition {
3
3
  Name: string;
4
4
  Description: string;
5
- InputSchema: {
6
- type: string;
7
- properties: {
8
- command: {
9
- type: string;
10
- description: string;
11
- };
12
- yield_time_s: {
13
- type: string;
14
- description: string;
15
- default: number;
16
- };
17
- task_id?: undefined;
18
- wait_time_s?: undefined;
19
- file_path?: undefined;
20
- offset?: undefined;
21
- limit?: undefined;
22
- old_string?: undefined;
23
- new_string?: undefined;
24
- replace_all?: undefined;
25
- };
26
- required: string[];
27
- };
28
- } | {
29
- Name: string;
30
- Description: string;
31
- InputSchema: {
32
- type: string;
33
- properties: {
34
- task_id: {
35
- type: string;
36
- description: string;
37
- };
38
- wait_time_s: {
39
- type: string;
40
- description: string;
41
- default: number;
42
- };
43
- command?: undefined;
44
- yield_time_s?: undefined;
45
- file_path?: undefined;
46
- offset?: undefined;
47
- limit?: undefined;
48
- old_string?: undefined;
49
- new_string?: undefined;
50
- replace_all?: undefined;
51
- };
52
- required: string[];
53
- };
54
- } | {
55
- Name: string;
56
- Description: string;
57
- InputSchema: {
58
- type: string;
59
- properties: {
60
- file_path: {
61
- type: string;
62
- };
63
- offset: {
64
- type: string;
65
- };
66
- limit: {
67
- type: string;
68
- };
69
- command?: undefined;
70
- yield_time_s?: undefined;
71
- task_id?: undefined;
72
- wait_time_s?: undefined;
73
- old_string?: undefined;
74
- new_string?: undefined;
75
- replace_all?: undefined;
76
- };
77
- required: string[];
78
- };
79
- } | {
80
- Name: string;
81
- Description: string;
82
- InputSchema: {
83
- type: string;
84
- properties: {
85
- file_path: {
86
- type: string;
87
- };
88
- old_string: {
89
- type: string;
90
- };
91
- new_string: {
92
- type: string;
93
- };
94
- replace_all: {
95
- type: string;
96
- };
97
- command?: undefined;
98
- yield_time_s?: undefined;
99
- task_id?: undefined;
100
- wait_time_s?: undefined;
101
- offset?: undefined;
102
- limit?: undefined;
103
- };
104
- required: string[];
105
- };
106
- })[];
5
+ InputSchema: Record<string, unknown>;
6
+ }
7
+ /**
8
+ * 一组前端工具,外加这一组自己的 system prompt。
9
+ *
10
+ * 工具定义只写「这是什么、入参是什么」,行为规则一律放在 guidance 里:
11
+ * 启用一组工具,就同时启用它的工具和它的 prompt,两者不会各说各的。
12
+ */
13
+ export interface CallerToolGroup {
14
+ id: string;
15
+ tools: CallerToolDefinition[];
16
+ /** 这一组注入 system prompt 的说明;空字符串表示只提供工具、不注入。 */
17
+ guidance: string;
18
+ }
19
+ export declare const CALLER_TOOL_GROUPS: CallerToolGroup[];
20
+ /** 启用所有组时要下发的工具。 */
21
+ export declare const CALLER_TOOLS: CallerToolDefinition[];
22
+ /** 把各组的 prompt 拼成一段,交给对话协议的 ToolGuidance。 */
23
+ export declare function composeCallerToolGuidance(groups?: readonly CallerToolGroup[]): string;
24
+ export declare const CALLER_TOOL_GUIDANCE: string;
107
25
  //# sourceMappingURL=callerTools.d.ts.map
@@ -1,20 +1,9 @@
1
1
  import { EXEC_YIELD_S, TASK_WAIT_S } from '../tools/local.js';
2
- export const TOOL_GUIDANCE = [
3
- '当前执行环境是调用方启动时所在的工作目录,命令和文件都在这台机器上,不在 Portal 沙箱里。',
4
- '用户说当前项目、当前文件夹,指的都是这个执行环境。',
5
- '在当前执行环境里,跑命令用 exec,读文件用 read,改文件用 edit。',
6
- 'exec 超过 yield_time_s 仍在运行时不会被杀掉,而是返回 task id;用 task_status 查看它是否结束以及新产生的输出。',
7
- 'task_status 自己会等:wait_time_s 内任务结束就直接拿到结果,没结束才返回当前进度,所以不要用 sleep 轮询。',
8
- '改已有文件前先 read。edit 按原文逐字替换;要插入时把插入点前后的原文放进 old_string,',
9
- 'new_string 保留这段原文并加上新内容。new_string 为空是删除。',
10
- 'project_storage 只放用户要下载的最终结果,不要用它读写当前执行环境里的代码。',
11
- '用 git 提交时,在提交消息末尾空一行,再加一行 "Co-authored-by: portal-cli"。',
12
- ].join('');
13
2
  const READ_LINE_LIMIT = 2000;
14
- export const CALLER_TOOLS = [
3
+ const localExecTools = [
15
4
  {
16
5
  Name: 'exec',
17
- Description: `在本地 bash 里执行一条命令,返回 stdout、stderr 和退出码。命令在 yield_time_s(秒,默认 ${EXEC_YIELD_S})内结束就直接返回结果;超过则转入后台并返回 task id,命令不会被杀掉,之后用 task_status 查看进度和输出。`,
6
+ Description: `在本地 bash 里执行一条命令,返回 stdout、stderr 和退出码。命令在 yield_time_s(秒,默认 ${EXEC_YIELD_S})内结束就直接返回结果;超过则转入后台并返回 task id。`,
18
7
  InputSchema: {
19
8
  type: 'object',
20
9
  properties: {
@@ -30,7 +19,7 @@ export const CALLER_TOOLS = [
30
19
  },
31
20
  {
32
21
  Name: 'task_status',
33
- Description: `查看后台任务(exec 转后台后返回的 task id)的状态:是否还在运行、退出码,以及自上次查看以来的新输出。任务还在运行时会先等 wait_time_s(秒,默认 ${TASK_WAIT_S}),期间结束就直接返回结果,没结束才返回当前进度,所以不需要用 sleep 轮询。不写入 stdin,所以交互式程序请改用命令行参数。`,
22
+ Description: `查看后台任务(exec 转后台后返回的 task id)的状态、退出码,以及自上次查看以来的新输出。会先等 wait_time_s(秒,默认 ${TASK_WAIT_S})。不写入 stdin。`,
34
23
  InputSchema: {
35
24
  type: 'object',
36
25
  properties: {
@@ -59,7 +48,7 @@ export const CALLER_TOOLS = [
59
48
  },
60
49
  {
61
50
  Name: 'edit',
62
- Description: '按原文逐字修改一个已有的 UTF-8 文本文件。old_string 必须逐字匹配。',
51
+ Description: '按原文逐字替换一个已有的 UTF-8 文本文件里的内容。',
63
52
  InputSchema: {
64
53
  type: 'object',
65
54
  properties: {
@@ -72,4 +61,82 @@ export const CALLER_TOOLS = [
72
61
  },
73
62
  },
74
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();
75
142
  //# sourceMappingURL=callerTools.js.map
@@ -1,16 +1,10 @@
1
- import type { ChatTurn, ContextUsage, ThoughtBlock, ToolCall, UserQuestion } from './types.js';
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: (question: UserQuestion) => Promise<string[][]>;
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>;
@@ -1,9 +1,7 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { createLocalTools } from '../tools/local.js';
3
- import { CALLER_TOOLS, TOOL_GUIDANCE } from './callerTools.js';
3
+ import { CALLER_TOOL_GUIDANCE, CALLER_TOOLS } from './callerTools.js';
4
4
  import { readChatStream } from './sse.js';
5
- export class QuestionDeclined extends Error {
6
- }
7
5
  // One per process: the CLI talks to one machine, so its background tasks live
8
6
  // as long as the process does.
9
7
  const defaultTools = createLocalTools();
@@ -13,7 +11,7 @@ export function chatBody(sessionId, turn) {
13
11
  ConversationId: sessionId,
14
12
  Contents: turn.contents,
15
13
  Tools: CALLER_TOOLS,
16
- ToolGuidance: TOOL_GUIDANCE,
14
+ ToolGuidance: CALLER_TOOL_GUIDANCE,
17
15
  Incremental: true,
18
16
  Stream: 'enable',
19
17
  ...(turn.previousResponseId ? { PreviousResponseId: turn.previousResponseId } : {}),
@@ -43,10 +41,6 @@ export async function runChat(input) {
43
41
  // Keep the latest reported window usage; a turn can span several streams
44
42
  // when local tools run in between.
45
43
  contextUsage = segment.contextUsage ?? contextUsage;
46
- if (segment.question) {
47
- response = replyToQuestion(input, segment.question);
48
- continue;
49
- }
50
44
  if (segment.completed || segment.calls.length === 0) {
51
45
  return { text, sessionTitle, ...(contextUsage ? { contextUsage } : {}) };
52
46
  }
@@ -57,22 +51,11 @@ export async function runChat(input) {
57
51
  CallId: call.callId,
58
52
  Output: input.onTool
59
53
  ? await input.onTool(call)
60
- : await defaultTools.run(input.cwd, call),
54
+ : await defaultTools.run(input.cwd, call, { ask: input.ask }),
61
55
  });
62
56
  }
63
57
  previousResponseId = segment.recordId;
64
58
  response = input.openStream({ contents, previousResponseId });
65
59
  }
66
60
  }
67
- async function replyToQuestion(input, question) {
68
- try {
69
- const answers = await input.ask(question);
70
- return input.replyQuestion(question, { answers });
71
- }
72
- catch (error) {
73
- if (!(error instanceof QuestionDeclined))
74
- throw error;
75
- return input.replyQuestion(question, { rejected: true });
76
- }
77
- }
78
61
  //# sourceMappingURL=chat.js.map
@@ -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;
@@ -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',
@@ -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;
@@ -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
@@ -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();
@@ -18,11 +18,12 @@ export interface UserQuestionItem {
18
18
  options: UserQuestionOption[];
19
19
  multiple?: boolean;
20
20
  }
21
- export interface UserQuestion {
22
- interactionId: string;
23
- version: number;
24
- questions: UserQuestionItem[];
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
@@ -1,4 +1,4 @@
1
- import type { ToolCall } from '../portal/types.js';
1
+ import type { AskUserReply, ToolCall, UserQuestionItem } from '../portal/types.js';
2
2
  import { BackgroundTasks } from './tasks.js';
3
3
  /** How long exec waits before handing the command over to the background, in seconds. */
4
4
  export declare const EXEC_YIELD_S = 10;
@@ -12,11 +12,14 @@ export interface LocalToolHost {
12
12
  output: string;
13
13
  }) => void;
14
14
  }
15
+ export declare const ASK_USER_TOOL_NAME = "ask_user";
15
16
  export interface RunOptions {
16
17
  /** The turn was cancelled: stop waiting, and stop the command. */
17
18
  signal?: AbortSignal;
18
19
  /** How long exec waits before handing the command over to the background, in seconds. */
19
20
  yieldS?: number;
21
+ /** How the user is asked when the model calls ask_user. */
22
+ ask?: (questions: UserQuestionItem[]) => Promise<AskUserReply>;
20
23
  }
21
24
  /** What a tool reports back when the turn was cancelled while it ran. */
22
25
  export declare const CANCELLED = "\u5DF2\u53D6\u6D88\uFF1A\u547D\u4EE4\u5DF2\u7EC8\u6B62\u3002";
@@ -7,6 +7,12 @@ export const EXEC_YIELD_S = 10;
7
7
  export const TASK_WAIT_S = 10;
8
8
  const MS_PER_S = 1000;
9
9
  const READ_LINE_LIMIT = 2000;
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;
10
16
  /** What a tool reports back when the turn was cancelled while it ran. */
11
17
  export const CANCELLED = '已取消:命令已终止。';
12
18
  /**
@@ -30,6 +36,8 @@ export function createLocalTools(host = {}) {
30
36
  return read(cwd, call.arguments);
31
37
  if (call.name === 'edit')
32
38
  return edit(cwd, call.arguments);
39
+ if (call.name === ASK_USER_TOOL_NAME)
40
+ return await runAskUser(call.arguments, options);
33
41
  return `Tool ${call.name} is not available in this environment.`;
34
42
  }
35
43
  catch (error) {
@@ -87,6 +95,66 @@ async function readTaskOutput(args, tasks, options) {
87
95
  snapshot.output,
88
96
  ].filter((part) => part.length > 0).join('\n');
89
97
  }
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 '当前环境无法展示交互式提问。请改用正文直接提问。';
109
+ }
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;
155
+ }
156
+ return questions;
157
+ }
90
158
  function read(cwd, args) {
91
159
  const filePath = String(args.file_path ?? args.path ?? '');
92
160
  const lines = fileLines(resolvePath(cwd, filePath));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tencent-adp/portal-cli",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "description": "Talk to a Portal agent and let it use this machine",
5
5
  "type": "module",
6
6
  "bin": {