@tencent-adp/portal-cli 0.0.3 → 0.0.5

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.
@@ -8,6 +8,14 @@ export declare class PortalAcpAgent {
8
8
  private readonly workbench;
9
9
  private readonly baseUrl;
10
10
  private readonly sessions;
11
+ private connection;
12
+ /**
13
+ * One task table for the whole agent: a command started in a turn outlives
14
+ * that turn, and its exit is what wakes the session back up.
15
+ */
16
+ private readonly tools;
17
+ /** Which session started each background task, so the exit reaches it. */
18
+ private readonly taskOwners;
11
19
  constructor(client: PortalClient, spaceId: string, workbench: WorkbenchTarget, baseUrl?: string);
12
20
  initialize(): InitializeResponse;
13
21
  newSession(params: NewSessionRequest): NewSessionResponse;
@@ -15,6 +23,32 @@ export declare class PortalAcpAgent {
15
23
  listSessions(params: ListSessionsRequest): ListSessionsResponse;
16
24
  setConfig(params: SetSessionConfigOptionRequest): SetSessionConfigOptionResponse;
17
25
  prompt(params: PromptRequest, acp: AgentContext): Promise<PromptResponse>;
26
+ /** Remembers which session started a task, so its exit reaches that session. */
27
+ private noteTaskOwner;
28
+ /**
29
+ * A background command finished. The model is told in a turn of its own, but
30
+ * only once the current turn is over: interrupting a reply the user is reading
31
+ * to announce a build would be worse than waiting.
32
+ */
33
+ private notifyTaskExit;
34
+ /**
35
+ * Delivers one queued background-task notice as its own turn.
36
+ *
37
+ * Returns as soon as the turn starts, so a caller finishing its own turn never
38
+ * waits on this one. The turn ends by re-entering drainQueue, which is what
39
+ * keeps a backlog flowing in arrival order.
40
+ */
41
+ private drainQueue;
42
+ /**
43
+ * Queues a notice, or starts its turn right away when nothing is running.
44
+ *
45
+ * A running turn is never interrupted: the notice waits for it to end, and
46
+ * prompt() drains the queue at that moment.
47
+ */
48
+ enqueueNotice(sessionId: string, text: string): void;
49
+ /** The connection-scoped client context, set once the transport connects. */
50
+ setConnectionContext(context: AgentContext): void;
51
+ private connectionContext;
18
52
  cancel(sessionId: string): void;
19
53
  private openSession;
20
54
  private record;
package/dist/acp/agent.js CHANGED
@@ -3,6 +3,7 @@ import { PROTOCOL_VERSION, RequestError } from '@agentclientprotocol/sdk';
3
3
  import { createSessionId } from '../cli/session.js';
4
4
  import { portalBaseUrl, readSessions, rememberSession } from '../cli/sessions.js';
5
5
  import { defaultReasoningEffort, isReasoningEffort, pickModel, } from '../portal/target.js';
6
+ import { createLocalTools } from '../tools/local.js';
6
7
  import { replayHistory } from './history.js';
7
8
  import { sessionConfigOptions } from './options.js';
8
9
  import { promptText } from './prompt.js';
@@ -10,7 +11,7 @@ import { runAcpTurn } from './turn.js';
10
11
  export function portalInitialize(needsLogin = false) {
11
12
  return {
12
13
  protocolVersion: PROTOCOL_VERSION,
13
- agentInfo: { name: 'portal', title: 'Portal', version: '0.0.3' },
14
+ agentInfo: { name: 'portal', title: 'Portal', version: '0.0.4' },
14
15
  agentCapabilities: {
15
16
  loadSession: true,
16
17
  sessionCapabilities: { list: {} },
@@ -26,6 +27,16 @@ export class PortalAcpAgent {
26
27
  workbench;
27
28
  baseUrl;
28
29
  sessions = new Map();
30
+ connection = null;
31
+ /**
32
+ * One task table for the whole agent: a command started in a turn outlives
33
+ * that turn, and its exit is what wakes the session back up.
34
+ */
35
+ tools = createLocalTools({
36
+ onTaskExit: (snapshot) => this.notifyTaskExit(snapshot),
37
+ });
38
+ /** Which session started each background task, so the exit reaches it. */
39
+ taskOwners = new Map();
29
40
  constructor(client, spaceId, workbench, baseUrl = '') {
30
41
  this.client = client;
31
42
  this.spaceId = spaceId;
@@ -103,6 +114,7 @@ export class PortalAcpAgent {
103
114
  session.abort?.abort();
104
115
  const abort = new AbortController();
105
116
  session.abort = abort;
117
+ session.turnActive = true;
106
118
  try {
107
119
  return await runAcpTurn({
108
120
  session,
@@ -113,6 +125,11 @@ export class PortalAcpAgent {
113
125
  acp,
114
126
  message: promptText(params.prompt),
115
127
  signal: abort.signal,
128
+ tools: this.tools,
129
+ onTaskStarted: (taskId) => this.noteTaskOwner(session.cwd, taskId),
130
+ // Checking a task is a safe point mid-turn: hand over what queued up
131
+ // rather than waiting for the turn to end.
132
+ onTaskChecked: () => session.queue.splice(0).map((notice) => notice.text),
116
133
  });
117
134
  }
118
135
  catch (error) {
@@ -123,8 +140,100 @@ export class PortalAcpAgent {
123
140
  finally {
124
141
  if (session.abort === abort)
125
142
  session.abort = null;
143
+ session.turnActive = false;
144
+ // The turn is over for any reason: this is where a queued background
145
+ // notice gets its turn. Nothing polls.
146
+ this.drainQueue(session);
126
147
  }
127
148
  }
149
+ /** Remembers which session started a task, so its exit reaches that session. */
150
+ noteTaskOwner(cwd, taskId) {
151
+ const session = [...this.sessions.values()].find((item) => item.cwd === cwd);
152
+ if (session)
153
+ this.taskOwners.set(taskId, session.id);
154
+ }
155
+ /**
156
+ * A background command finished. The model is told in a turn of its own, but
157
+ * only once the current turn is over: interrupting a reply the user is reading
158
+ * to announce a build would be worse than waiting.
159
+ */
160
+ notifyTaskExit(snapshot) {
161
+ const sessionId = this.taskOwners.get(snapshot.taskId);
162
+ if (!sessionId)
163
+ return;
164
+ this.taskOwners.delete(snapshot.taskId);
165
+ const status = snapshot.exitCode === null
166
+ ? '已退出(退出码未知)'
167
+ : `已退出(exit ${snapshot.exitCode})`;
168
+ const output = snapshot.output.trim().length > 0
169
+ ? `\n\n输出:\n${snapshot.output.trim()}`
170
+ : '\n\n(没有输出)';
171
+ this.enqueueNotice(sessionId, `后台任务 ${snapshot.taskId} ${status}。${output}`);
172
+ }
173
+ /**
174
+ * Delivers one queued background-task notice as its own turn.
175
+ *
176
+ * Returns as soon as the turn starts, so a caller finishing its own turn never
177
+ * waits on this one. The turn ends by re-entering drainQueue, which is what
178
+ * keeps a backlog flowing in arrival order.
179
+ */
180
+ drainQueue(session) {
181
+ if (session.turnActive)
182
+ return;
183
+ const next = session.queue.shift();
184
+ if (!next)
185
+ return;
186
+ session.turnActive = true;
187
+ const abort = new AbortController();
188
+ session.abort = abort;
189
+ void runAcpTurn({
190
+ session,
191
+ client: this.client,
192
+ spaceId: this.spaceId,
193
+ agentId: this.workbench.agentId,
194
+ models: this.workbench.models,
195
+ // The connection-scoped context: a request-scoped one belongs to a prompt
196
+ // that has already returned, so its notifications have nowhere to go.
197
+ acp: this.connectionContext(),
198
+ message: next.text,
199
+ signal: abort.signal,
200
+ tools: this.tools,
201
+ })
202
+ .catch((error) => {
203
+ if (!abort.signal.aborted) {
204
+ console.error(`background turn failed: ${error instanceof Error ? error.stack : String(error)}`);
205
+ }
206
+ })
207
+ .finally(() => {
208
+ if (session.abort === abort)
209
+ session.abort = null;
210
+ session.turnActive = false;
211
+ this.drainQueue(session);
212
+ });
213
+ }
214
+ /**
215
+ * Queues a notice, or starts its turn right away when nothing is running.
216
+ *
217
+ * A running turn is never interrupted: the notice waits for it to end, and
218
+ * prompt() drains the queue at that moment.
219
+ */
220
+ enqueueNotice(sessionId, text) {
221
+ const session = this.sessions.get(sessionId);
222
+ if (!session)
223
+ return;
224
+ session.queue.push({ text });
225
+ if (!session.turnActive)
226
+ this.drainQueue(session);
227
+ }
228
+ /** The connection-scoped client context, set once the transport connects. */
229
+ setConnectionContext(context) {
230
+ this.connection = context;
231
+ }
232
+ connectionContext() {
233
+ if (!this.connection)
234
+ throw new Error('ACP connection context is not ready yet');
235
+ return this.connection;
236
+ }
128
237
  cancel(sessionId) {
129
238
  this.sessions.get(sessionId)?.abort?.abort();
130
239
  }
@@ -155,6 +264,8 @@ export class PortalAcpAgent {
155
264
  : defaultReasoningEffort(model, process.env.PORTAL_REASONING_EFFORT || this.workbench.defaultReasoningEffort),
156
265
  sentThoughts: new Map(),
157
266
  abort: null,
267
+ turnActive: false,
268
+ queue: [],
158
269
  };
159
270
  this.sessions.set(id, session);
160
271
  return session;
@@ -8,9 +8,16 @@ import { PortalAcpAgent, portalInitialize } from './agent.js';
8
8
  export async function serveAcp() {
9
9
  let started;
10
10
  let canShowLoginUrl = false;
11
+ // The connection-scoped context. It exists before any request arrives, which
12
+ // is what lets a background task notify the client outside a prompt.
13
+ let connection;
11
14
  const stream = acp.ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin));
12
15
  const start = (interactive, request) => {
13
- const run = createAgent(interactive, request, canShowLoginUrl);
16
+ const run = createAgent(interactive, request, canShowLoginUrl).then((agent) => {
17
+ if (connection)
18
+ agent.setConnectionContext(connection);
19
+ return agent;
20
+ });
14
21
  started = run;
15
22
  run.catch(() => {
16
23
  if (started === run)
@@ -26,6 +33,12 @@ export async function serveAcp() {
26
33
  return start(false);
27
34
  };
28
35
  acp.agent({ name: 'portal' })
36
+ .onConnect((ctx) => {
37
+ connection = ctx.client;
38
+ // An agent may already exist from a previous connection; hand it the new
39
+ // context so background notices keep a live channel.
40
+ void started?.then((agent) => agent.setConnectionContext(ctx.client)).catch(() => undefined);
41
+ })
29
42
  .onRequest(acp.methods.agent.initialize, (ctx) => {
30
43
  canShowLoginUrl = ctx.params.clientCapabilities?.elicitation?.url != null;
31
44
  return portalInitialize(browserLoginRequired());
@@ -1,3 +1,7 @@
1
+ /** A background task that finished while a turn was still running. */
2
+ export interface QueuedNotice {
3
+ text: string;
4
+ }
1
5
  export interface AcpSession {
2
6
  id: string;
3
7
  cwd: string;
@@ -8,5 +12,15 @@ export interface AcpSession {
8
12
  /** Reasoning text already sent to the client, keyed by thought messageId. */
9
13
  sentThoughts: Map<string, string>;
10
14
  abort: AbortController | null;
15
+ /**
16
+ * True while a turn is running. A turn ends for any reason (reply, error,
17
+ * cancel) and the queue is drained at that moment, so no polling is needed.
18
+ */
19
+ turnActive: boolean;
20
+ /**
21
+ * Background-task notices that arrived while a turn was running. FIFO: each
22
+ * one is delivered as its own turn, in arrival order.
23
+ */
24
+ queue: QueuedNotice[];
11
25
  }
12
26
  //# sourceMappingURL=session.d.ts.map
@@ -1,6 +1,7 @@
1
1
  import { type AgentContext, type PromptResponse } from '@agentclientprotocol/sdk';
2
2
  import type { PortalClient } from '../portal/client.js';
3
3
  import type { RuntimeModel } from '../portal/target.js';
4
+ import type { createLocalTools } from '../tools/local.js';
4
5
  import type { AcpSession } from './session.js';
5
6
  export declare function runAcpTurn(input: {
6
7
  session: AcpSession;
@@ -11,5 +12,8 @@ export declare function runAcpTurn(input: {
11
12
  models: RuntimeModel[];
12
13
  message: string;
13
14
  signal: AbortSignal;
15
+ tools: ReturnType<typeof createLocalTools>;
16
+ onTaskStarted?: (taskId: string) => void;
17
+ onTaskChecked?: () => string[];
14
18
  }): Promise<PromptResponse>;
15
19
  //# sourceMappingURL=turn.d.ts.map
package/dist/acp/turn.js CHANGED
@@ -2,7 +2,6 @@ import path from 'node:path';
2
2
  import { methods } from '@agentclientprotocol/sdk';
3
3
  import { rememberSession } from '../cli/sessions.js';
4
4
  import { chatBody, QuestionDeclined, runChat } from '../portal/chat.js';
5
- import { runLocalTool } from '../tools/local.js';
6
5
  export async function runAcpTurn(input) {
7
6
  const result = await runChat({
8
7
  message: input.message,
@@ -130,15 +129,27 @@ async function reportTool(input, call) {
130
129
  rawInput: call.arguments,
131
130
  ...(filePath ? { locations: [{ path: path.resolve(input.session.cwd, filePath) }] } : {}),
132
131
  });
133
- const output = await runLocalTool(input.session.cwd, call);
132
+ const output = await input.tools.run(input.session.cwd, call, { signal: input.signal });
133
+ // A command now running in the background must wake this session when it
134
+ // exits, so remember which session started it.
135
+ const task = /^background task started: (\S+)/m.exec(output);
136
+ if (task?.[1])
137
+ input.onTaskStarted?.(task[1]);
138
+ // A status check means the caller is looking at task progress, so this is the
139
+ // safe point to deliver notices that queued up during this turn. They ride
140
+ // along with this tool result instead of interrupting the turn with another.
141
+ const notices = call.name === 'task_status' ? input.onTaskChecked?.() ?? [] : [];
142
+ const reported = notices.length > 0
143
+ ? `${output}\n\n${notices.join('\n\n')}`
144
+ : output;
134
145
  await update(input, {
135
146
  sessionUpdate: 'tool_call_update',
136
147
  toolCallId: call.callId,
137
148
  status: 'completed',
138
- rawOutput: output,
139
- content: [{ type: 'content', content: { type: 'text', text: output } }],
149
+ rawOutput: reported,
150
+ content: [{ type: 'content', content: { type: 'text', text: reported } }],
140
151
  });
141
- return output;
152
+ return reported;
142
153
  }
143
154
  function toolKind(name) {
144
155
  if (name === 'exec')
@@ -59,12 +59,15 @@ async function login(saved, showUrl) {
59
59
  });
60
60
  console.error('请在浏览器打开这个地址,登录 Portal,并选择要授权的空间。');
61
61
  console.error(url);
62
- openBrowser(url);
63
62
  if (showUrl) {
63
+ // Zed shows its own Open button. Opening the browser here races that prompt.
64
64
  void Promise.resolve(showUrl(url)).catch((error) => {
65
65
  console.error(errorText(error));
66
66
  });
67
67
  }
68
+ else {
69
+ openBrowser(url);
70
+ }
68
71
  const code = await withTimeout(callback.code, 5 * 60 * 1000);
69
72
  const tokens = await exchangeCode({
70
73
  tokenEndpoint: endpoints.tokenEndpoint,
@@ -9,6 +9,39 @@ export declare const CALLER_TOOLS: ({
9
9
  type: string;
10
10
  description: string;
11
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;
12
45
  file_path?: undefined;
13
46
  offset?: undefined;
14
47
  limit?: undefined;
@@ -34,6 +67,9 @@ export declare const CALLER_TOOLS: ({
34
67
  type: string;
35
68
  };
36
69
  command?: undefined;
70
+ yield_time_s?: undefined;
71
+ task_id?: undefined;
72
+ wait_time_s?: undefined;
37
73
  old_string?: undefined;
38
74
  new_string?: undefined;
39
75
  replace_all?: undefined;
@@ -59,6 +95,9 @@ export declare const CALLER_TOOLS: ({
59
95
  type: string;
60
96
  };
61
97
  command?: undefined;
98
+ yield_time_s?: undefined;
99
+ task_id?: undefined;
100
+ wait_time_s?: undefined;
62
101
  offset?: undefined;
63
102
  limit?: undefined;
64
103
  };
@@ -1,24 +1,49 @@
1
+ import { EXEC_YIELD_S, TASK_WAIT_S } from '../tools/local.js';
1
2
  export const TOOL_GUIDANCE = [
2
3
  '当前执行环境是调用方启动时所在的工作目录,命令和文件都在这台机器上,不在 Portal 沙箱里。',
3
4
  '用户说当前项目、当前文件夹,指的都是这个执行环境。',
4
5
  '在当前执行环境里,跑命令用 exec,读文件用 read,改文件用 edit。',
6
+ 'exec 超过 yield_time_s 仍在运行时不会被杀掉,而是返回 task id;用 task_status 查看它是否结束以及新产生的输出。',
7
+ 'task_status 自己会等:wait_time_s 内任务结束就直接拿到结果,没结束才返回当前进度,所以不要用 sleep 轮询。',
5
8
  '改已有文件前先 read。edit 按原文逐字替换;要插入时把插入点前后的原文放进 old_string,',
6
9
  'new_string 保留这段原文并加上新内容。new_string 为空是删除。',
7
10
  'project_storage 只放用户要下载的最终结果,不要用它读写当前执行环境里的代码。',
11
+ '用 git 提交时,在提交消息末尾空一行,再加一行 "Co-authored-by: portal-cli"。',
8
12
  ].join('');
9
13
  const READ_LINE_LIMIT = 2000;
10
14
  export const CALLER_TOOLS = [
11
15
  {
12
16
  Name: 'exec',
13
- Description: '在本地 bash 里执行一条命令,返回 stdout、stderr 和退出码。',
17
+ Description: `在本地 bash 里执行一条命令,返回 stdout、stderr 和退出码。命令在 yield_time_s(秒,默认 ${EXEC_YIELD_S})内结束就直接返回结果;超过则转入后台并返回 task id,命令不会被杀掉,之后用 task_status 查看进度和输出。`,
14
18
  InputSchema: {
15
19
  type: 'object',
16
20
  properties: {
17
21
  command: { type: 'string', description: '要执行的 shell 命令' },
22
+ yield_time_s: {
23
+ type: 'number',
24
+ description: `等待多久后转后台,秒,默认 ${EXEC_YIELD_S}。`,
25
+ default: EXEC_YIELD_S,
26
+ },
18
27
  },
19
28
  required: ['command'],
20
29
  },
21
30
  },
31
+ {
32
+ Name: 'task_status',
33
+ Description: `查看后台任务(exec 转后台后返回的 task id)的状态:是否还在运行、退出码,以及自上次查看以来的新输出。任务还在运行时会先等 wait_time_s(秒,默认 ${TASK_WAIT_S}),期间结束就直接返回结果,没结束才返回当前进度,所以不需要用 sleep 轮询。不写入 stdin,所以交互式程序请改用命令行参数。`,
34
+ InputSchema: {
35
+ type: 'object',
36
+ properties: {
37
+ task_id: { type: 'string', description: 'exec 返回的 task id' },
38
+ wait_time_s: {
39
+ type: 'number',
40
+ description: `最多等多久,秒,默认 ${TASK_WAIT_S}。`,
41
+ default: TASK_WAIT_S,
42
+ },
43
+ },
44
+ required: ['task_id'],
45
+ },
46
+ },
22
47
  {
23
48
  Name: 'read',
24
49
  Description: `读取本地 UTF-8 文本文件。offset 从 1 开始,limit 最多 ${READ_LINE_LIMIT} 行。`,
@@ -1,9 +1,12 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { runLocalTool } from '../tools/local.js';
2
+ import { createLocalTools } from '../tools/local.js';
3
3
  import { CALLER_TOOLS, TOOL_GUIDANCE } from './callerTools.js';
4
4
  import { readChatStream } from './sse.js';
5
5
  export class QuestionDeclined extends Error {
6
6
  }
7
+ // One per process: the CLI talks to one machine, so its background tasks live
8
+ // as long as the process does.
9
+ const defaultTools = createLocalTools();
7
10
  export function chatBody(sessionId, turn) {
8
11
  return {
9
12
  RequestId: randomBytes(16).toString('hex'),
@@ -52,7 +55,9 @@ export async function runChat(input) {
52
55
  contents.push({
53
56
  Type: 'function_call_output',
54
57
  CallId: call.callId,
55
- Output: input.onTool ? await input.onTool(call) : await runLocalTool(input.cwd, call),
58
+ Output: input.onTool
59
+ ? await input.onTool(call)
60
+ : await defaultTools.run(input.cwd, call),
56
61
  });
57
62
  }
58
63
  previousResponseId = segment.recordId;
@@ -1,3 +1,33 @@
1
1
  import type { ToolCall } from '../portal/types.js';
2
- export declare function runLocalTool(cwd: string, call: ToolCall, timeoutMs?: number): Promise<string>;
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 interface RunOptions {
16
+ /** The turn was cancelled: stop waiting, and stop the command. */
17
+ signal?: AbortSignal;
18
+ /** How long exec waits before handing the command over to the background, in seconds. */
19
+ yieldS?: number;
20
+ }
21
+ /** What a tool reports back when the turn was cancelled while it ran. */
22
+ export declare const CANCELLED = "\u5DF2\u53D6\u6D88\uFF1A\u547D\u4EE4\u5DF2\u7EC8\u6B62\u3002";
23
+ /**
24
+ * Runs the tools the model calls against this machine.
25
+ *
26
+ * A command that outlives `yield_time_ms` is not killed: it keeps running and
27
+ * the caller is handed a task id, so a long build does not block the turn.
28
+ */
29
+ export declare function createLocalTools(host?: LocalToolHost): {
30
+ tasks: BackgroundTasks;
31
+ run(cwd: string, call: ToolCall, options?: RunOptions): Promise<string>;
32
+ };
3
33
  //# sourceMappingURL=local.d.ts.map
@@ -1,72 +1,91 @@
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 EXEC_TIMEOUT_MS = 60_000;
6
- export async function runLocalTool(cwd, call, timeoutMs = EXEC_TIMEOUT_MS) {
7
- try {
8
- if (call.name === 'exec')
9
- return await exec(cwd, String(call.arguments.command ?? ''), timeoutMs);
10
- if (call.name === 'read')
11
- return read(cwd, call.arguments);
12
- if (call.name === 'edit')
13
- return edit(cwd, call.arguments);
14
- return `Tool ${call.name} is not available in this environment.`;
15
- }
16
- catch (error) {
17
- return error instanceof Error ? error.message : String(error);
18
- }
19
- }
20
- function exec(cwd, command, timeoutMs) {
21
- return new Promise((resolve) => {
22
- const signal = AbortSignal.timeout(timeoutMs);
23
- // detached so the shell is its own process group and a timeout can stop
24
- // the command it launched, not only the shell.
25
- const child = spawn(command, { cwd, shell: true, detached: true, signal });
26
- let stdout = '';
27
- let stderr = '';
28
- let settled = false;
29
- const finish = (text) => {
30
- if (settled)
31
- return;
32
- settled = true;
33
- resolve(text);
34
- };
35
- child.stdout.setEncoding('utf8');
36
- child.stderr.setEncoding('utf8');
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
+ /** What a tool reports back when the turn was cancelled while it ran. */
11
+ export const CANCELLED = '已取消:命令已终止。';
12
+ /**
13
+ * Runs the tools the model calls against this machine.
14
+ *
15
+ * A command that outlives `yield_time_ms` is not killed: it keeps running and
16
+ * the caller is handed a task id, so a long build does not block the turn.
17
+ */
18
+ export function createLocalTools(host = {}) {
19
+ const tasks = new BackgroundTasks();
20
+ return {
21
+ tasks,
22
+ async run(cwd, call, options = {}) {
23
+ try {
24
+ if (call.name === 'exec') {
25
+ return await runExec(cwd, call.arguments, tasks, host, options);
26
+ }
27
+ if (call.name === 'task_status')
28
+ return await readTaskOutput(call.arguments, tasks, options);
29
+ if (call.name === 'read')
30
+ return read(cwd, call.arguments);
31
+ if (call.name === 'edit')
32
+ return edit(cwd, call.arguments);
33
+ return `Tool ${call.name} is not available in this environment.`;
34
+ }
35
+ catch (error) {
36
+ return error instanceof Error ? error.message : String(error);
50
37
  }
51
- finish(code ? `${stdout}\n[exit ${code}]\n${stderr}`.trim() : stdout);
52
- });
53
- });
38
+ },
39
+ };
54
40
  }
55
- function timeoutResult(stdout, stderr, timeoutMs) {
56
- const seconds = timeoutMs / 1000;
57
- const notice = `command timed out after ${seconds}s`;
58
- return [stdout.trimEnd(), stderr.trimEnd(), notice].filter((part) => part.length > 0).join('\n');
41
+ /**
42
+ * Reads a window given in seconds and hands back milliseconds for the timers.
43
+ * Seconds carry fractions, so 0.5 is a valid window.
44
+ */
45
+ function windowMs(args, key, fallbackS, allowZero) {
46
+ const raw = args[key];
47
+ const value = typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : raw;
48
+ const usable = typeof value === 'number' && Number.isFinite(value) && (allowZero ? value >= 0 : value > 0);
49
+ return Math.max(0, Math.round((usable ? value : fallbackS) * MS_PER_S));
59
50
  }
60
- function stopCommand(child) {
61
- if (!child.pid)
62
- return;
63
- try {
64
- process.kill(-child.pid, 'SIGKILL');
65
- }
66
- catch (error) {
67
- if (error.code !== 'ESRCH')
68
- throw error;
51
+ async function runExec(cwd, args, tasks, host, options) {
52
+ const command = String(args.command ?? '');
53
+ const task = tasks.start(cwd, command, host.onTaskExit);
54
+ const window = windowMs(args, 'yield_time_s', options.yieldS ?? EXEC_YIELD_S, false);
55
+ const snapshot = await tasks.wait(task.id, window, options.signal);
56
+ // The command ended inside the window: its output is the answer.
57
+ if (snapshot && !snapshot.running)
58
+ return snapshot.output;
59
+ // The user stopped the turn. Nothing will be handed back to the model, so
60
+ // nobody could ever read the task later: take the command down with it.
61
+ if (options.signal?.aborted) {
62
+ tasks.stop(task.id);
63
+ return CANCELLED;
69
64
  }
65
+ // Still running: hand over the id. Output so far comes along so an error that
66
+ // happened early is not lost while the command keeps going. This is the
67
+ // snapshot the window already read, so nothing is drained twice.
68
+ return [
69
+ `background task started: ${task.id}`,
70
+ 'it is still running; check it with task_status(task_id="' + task.id + '")',
71
+ snapshot?.output ? `output so far:\n${snapshot.output}` : '',
72
+ ].filter((part) => part.length > 0).join('\n');
73
+ }
74
+ async function readTaskOutput(args, tasks, options) {
75
+ const taskId = String(args.task_id ?? '');
76
+ const waitMs = options.signal?.aborted ? 0 : windowMs(args, 'wait_time_s', TASK_WAIT_S, true);
77
+ const snapshot = taskId ? await tasks.wait(taskId, waitMs, options.signal) : null;
78
+ if (!snapshot)
79
+ return `unknown task: ${taskId}`;
80
+ if (snapshot.running && options.signal?.aborted)
81
+ return `${taskId}: 已取消`;
82
+ const status = snapshot.running
83
+ ? 'still running'
84
+ : `exited with code ${snapshot.exitCode ?? 'null'}`;
85
+ return [
86
+ `${taskId}: ${status}`,
87
+ snapshot.output,
88
+ ].filter((part) => part.length > 0).join('\n');
70
89
  }
71
90
  function read(cwd, args) {
72
91
  const filePath = String(args.file_path ?? args.path ?? '');
@@ -0,0 +1,47 @@
1
+ import { type ChildProcess } from 'node:child_process';
2
+ export interface TaskSnapshot {
3
+ taskId: string;
4
+ running: boolean;
5
+ exitCode: number | null;
6
+ /** Output the caller has not seen yet. */
7
+ output: string;
8
+ }
9
+ interface Task {
10
+ id: string;
11
+ child: ChildProcess;
12
+ stdout: string;
13
+ stderr: string;
14
+ /** How much of stdout/stderr the caller has already been given. */
15
+ stdoutCursor: number;
16
+ stderrCursor: number;
17
+ running: boolean;
18
+ exitCode: number | null;
19
+ /** One-shot callers blocked in `wait()`, resolved with the exit. */
20
+ waiters: Array<(snapshot: TaskSnapshot) => void>;
21
+ }
22
+ /**
23
+ * Commands that outlive the wait window.
24
+ *
25
+ * A task never gets killed for taking too long: the caller is only told that it
26
+ * is still running, and can read its output later. Killing stays the caller's
27
+ * decision.
28
+ */
29
+ export declare class BackgroundTasks {
30
+ private readonly tasks;
31
+ private nextId;
32
+ start(cwd: string, command: string, onExit?: (snapshot: TaskSnapshot) => void): Task;
33
+ /** Reads what is new since the last call. Reading does not consume the task. */
34
+ snapshot(taskId: string): TaskSnapshot | null;
35
+ /**
36
+ * Waits up to `waitMs` for the task to exit, then reports what is new.
37
+ *
38
+ * This is what makes polling cheap: the caller blocks for one window instead
39
+ * of sleeping between reads, and gets the result the moment it exists. An
40
+ * abort (the user stopped the turn) resolves immediately.
41
+ */
42
+ wait(taskId: string, waitMs: number, signal?: AbortSignal): Promise<TaskSnapshot | null>;
43
+ stop(taskId: string): boolean;
44
+ get(taskId: string): Task | undefined;
45
+ }
46
+ export {};
47
+ //# sourceMappingURL=tasks.d.ts.map
@@ -0,0 +1,127 @@
1
+ import { spawn } from 'node:child_process';
2
+ /** How much of a stream to keep. Long-running commands can print a lot. */
3
+ const OUTPUT_LIMIT = 1_000_000;
4
+ /**
5
+ * Commands that outlive the wait window.
6
+ *
7
+ * A task never gets killed for taking too long: the caller is only told that it
8
+ * is still running, and can read its output later. Killing stays the caller's
9
+ * decision.
10
+ */
11
+ export class BackgroundTasks {
12
+ tasks = new Map();
13
+ nextId = 1;
14
+ start(cwd, command, onExit) {
15
+ const id = `task_${this.nextId++}`;
16
+ // detached: the shell becomes its own process group, so the whole tree can
17
+ // be stopped as one unit and outlives the tool call that started it.
18
+ const child = spawn(command, { cwd, shell: true, detached: true });
19
+ const task = {
20
+ id,
21
+ child,
22
+ stdout: '',
23
+ stderr: '',
24
+ stdoutCursor: 0,
25
+ stderrCursor: 0,
26
+ running: true,
27
+ exitCode: null,
28
+ waiters: [],
29
+ };
30
+ this.tasks.set(id, task);
31
+ child.stdout?.setEncoding('utf8');
32
+ child.stderr?.setEncoding('utf8');
33
+ child.stdout?.on('data', (chunk) => { task.stdout = append(task.stdout, chunk); });
34
+ child.stderr?.on('data', (chunk) => { task.stderr = append(task.stderr, chunk); });
35
+ const settle = (code) => {
36
+ if (!task.running)
37
+ return;
38
+ task.running = false;
39
+ task.exitCode = code;
40
+ const waiters = task.waiters.splice(0);
41
+ // Nobody wants the exit: leave the bytes unread for the next call.
42
+ if (waiters.length === 0 && !onExit)
43
+ return;
44
+ // Read the exit exactly once: the bytes may go to a caller that was
45
+ // waiting for them, or to the exit notice, never to both. Incremental
46
+ // like every other read, so what the caller was already shown stays out.
47
+ const exitSnapshot = this.snapshot(id);
48
+ for (const waiter of waiters)
49
+ waiter(exitSnapshot);
50
+ // Nobody was waiting: the exit has to reach the model as a turn of its
51
+ // own. A call that saw the exit has already reported it.
52
+ if (waiters.length === 0)
53
+ onExit?.(exitSnapshot);
54
+ };
55
+ child.on('error', () => settle(null));
56
+ child.on('close', (code) => settle(code));
57
+ return task;
58
+ }
59
+ /** Reads what is new since the last call. Reading does not consume the task. */
60
+ snapshot(taskId) {
61
+ const task = this.tasks.get(taskId);
62
+ if (!task)
63
+ return null;
64
+ const stdout = task.stdout.slice(task.stdoutCursor);
65
+ const stderr = task.stderr.slice(task.stderrCursor);
66
+ task.stdoutCursor = task.stdout.length;
67
+ task.stderrCursor = task.stderr.length;
68
+ const parts = [stdout.trimEnd(), stderr.trimEnd()].filter((part) => part.length > 0);
69
+ return { taskId: task.id, running: task.running, exitCode: task.exitCode, output: parts.join('\n') };
70
+ }
71
+ /**
72
+ * Waits up to `waitMs` for the task to exit, then reports what is new.
73
+ *
74
+ * This is what makes polling cheap: the caller blocks for one window instead
75
+ * of sleeping between reads, and gets the result the moment it exists. An
76
+ * abort (the user stopped the turn) resolves immediately.
77
+ */
78
+ wait(taskId, waitMs, signal) {
79
+ const task = this.tasks.get(taskId);
80
+ if (!task)
81
+ return Promise.resolve(null);
82
+ if (!task.running || signal?.aborted)
83
+ return Promise.resolve(this.snapshot(taskId));
84
+ return new Promise((resolve) => {
85
+ let settled = false;
86
+ const finish = (snapshot) => {
87
+ if (settled)
88
+ return;
89
+ settled = true;
90
+ clearTimeout(timer);
91
+ signal?.removeEventListener('abort', onAbort);
92
+ const index = task.waiters.indexOf(waiter);
93
+ if (index >= 0)
94
+ task.waiters.splice(index, 1);
95
+ resolve(snapshot);
96
+ };
97
+ const waiter = (snapshot) => finish(snapshot);
98
+ const onAbort = () => finish(this.snapshot(taskId));
99
+ const timer = setTimeout(() => finish(this.snapshot(taskId)), Math.max(0, waitMs));
100
+ task.waiters.push(waiter);
101
+ signal?.addEventListener('abort', onAbort, { once: true });
102
+ });
103
+ }
104
+ stop(taskId) {
105
+ const task = this.tasks.get(taskId);
106
+ if (!task || !task.running)
107
+ return false;
108
+ if (task.child.pid) {
109
+ try {
110
+ process.kill(-task.child.pid, 'SIGKILL');
111
+ }
112
+ catch (error) {
113
+ if (error.code !== 'ESRCH')
114
+ throw error;
115
+ }
116
+ }
117
+ return true;
118
+ }
119
+ get(taskId) {
120
+ return this.tasks.get(taskId);
121
+ }
122
+ }
123
+ function append(current, chunk) {
124
+ const next = current + chunk;
125
+ return next.length > OUTPUT_LIMIT ? next.slice(next.length - OUTPUT_LIMIT) : next;
126
+ }
127
+ //# sourceMappingURL=tasks.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tencent-adp/portal-cli",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "Talk to a Portal agent and let it use this machine",
5
5
  "type": "module",
6
6
  "bin": {