@tencent-adp/portal-cli 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/acp/agent.d.ts +25 -0
  2. package/dist/acp/agent.js +195 -0
  3. package/dist/acp/history.d.ts +15 -0
  4. package/dist/acp/history.js +41 -0
  5. package/dist/acp/options.d.ts +9 -0
  6. package/dist/acp/options.js +45 -0
  7. package/dist/acp/prompt.d.ts +3 -0
  8. package/dist/acp/prompt.js +10 -0
  9. package/dist/acp/server.d.ts +2 -0
  10. package/dist/acp/server.js +96 -0
  11. package/dist/acp/session.d.ts +12 -0
  12. package/dist/acp/session.js +2 -0
  13. package/dist/acp/turn.d.ts +15 -0
  14. package/dist/acp/turn.js +158 -0
  15. package/dist/auth/loadAuth.d.ts +22 -0
  16. package/dist/auth/loadAuth.js +54 -0
  17. package/dist/auth/login.d.ts +28 -0
  18. package/dist/auth/login.js +339 -0
  19. package/dist/bin.d.ts +3 -0
  20. package/dist/bin.js +24 -0
  21. package/dist/cli/ask.d.ts +3 -0
  22. package/dist/cli/ask.js +30 -0
  23. package/dist/cli/chat.d.ts +5 -0
  24. package/dist/cli/chat.js +48 -0
  25. package/dist/cli/session.d.ts +2 -0
  26. package/dist/cli/session.js +6 -0
  27. package/dist/cli/sessions.d.ts +20 -0
  28. package/dist/cli/sessions.js +56 -0
  29. package/dist/portal/callerTools.d.ts +68 -0
  30. package/dist/portal/callerTools.js +50 -0
  31. package/dist/portal/chat.d.ts +23 -0
  32. package/dist/portal/chat.js +73 -0
  33. package/dist/portal/client.d.ts +29 -0
  34. package/dist/portal/client.js +98 -0
  35. package/dist/portal/headers.d.ts +3 -0
  36. package/dist/portal/headers.js +5 -0
  37. package/dist/portal/sse.d.ts +9 -0
  38. package/dist/portal/sse.js +219 -0
  39. package/dist/portal/sseLog.d.ts +4 -0
  40. package/dist/portal/sseLog.js +47 -0
  41. package/dist/portal/target.d.ts +40 -0
  42. package/dist/portal/target.js +72 -0
  43. package/dist/portal/types.d.ts +53 -0
  44. package/dist/portal/types.js +2 -0
  45. package/dist/tools/local.d.ts +3 -0
  46. package/dist/tools/local.js +122 -0
  47. package/package.json +36 -3
  48. package/README.md +0 -3
@@ -0,0 +1,25 @@
1
+ import type { AgentContext, InitializeResponse, ListSessionsRequest, ListSessionsResponse, LoadSessionRequest, LoadSessionResponse, NewSessionRequest, NewSessionResponse, PromptRequest, PromptResponse, SetSessionConfigOptionRequest, SetSessionConfigOptionResponse } from '@agentclientprotocol/sdk';
2
+ import type { PortalClient } from '../portal/client.js';
3
+ import { type WorkbenchTarget } from '../portal/target.js';
4
+ export declare function portalInitialize(needsLogin?: boolean): InitializeResponse;
5
+ export declare class PortalAcpAgent {
6
+ private readonly client;
7
+ private readonly spaceId;
8
+ private readonly workbench;
9
+ private readonly baseUrl;
10
+ private readonly sessions;
11
+ constructor(client: PortalClient, spaceId: string, workbench: WorkbenchTarget, baseUrl?: string);
12
+ initialize(): InitializeResponse;
13
+ newSession(params: NewSessionRequest): NewSessionResponse;
14
+ loadSession(params: LoadSessionRequest, acp: AgentContext): Promise<LoadSessionResponse>;
15
+ listSessions(params: ListSessionsRequest): ListSessionsResponse;
16
+ setConfig(params: SetSessionConfigOptionRequest): SetSessionConfigOptionResponse;
17
+ prompt(params: PromptRequest, acp: AgentContext): Promise<PromptResponse>;
18
+ cancel(sessionId: string): void;
19
+ private openSession;
20
+ private record;
21
+ private requireSession;
22
+ private model;
23
+ private options;
24
+ }
25
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1,195 @@
1
+ import path from 'node:path';
2
+ import { PROTOCOL_VERSION, RequestError } from '@agentclientprotocol/sdk';
3
+ import { createSessionId } from '../cli/session.js';
4
+ import { portalBaseUrl, readSessions, rememberSession } from '../cli/sessions.js';
5
+ import { defaultReasoningEffort, isReasoningEffort, pickModel, } from '../portal/target.js';
6
+ import { replayHistory } from './history.js';
7
+ import { sessionConfigOptions } from './options.js';
8
+ import { promptText } from './prompt.js';
9
+ import { runAcpTurn } from './turn.js';
10
+ export function portalInitialize(needsLogin = false) {
11
+ return {
12
+ protocolVersion: PROTOCOL_VERSION,
13
+ agentInfo: { name: 'portal', title: 'Portal', version: '0.0.2' },
14
+ agentCapabilities: {
15
+ loadSession: true,
16
+ sessionCapabilities: { list: {} },
17
+ },
18
+ authMethods: needsLogin
19
+ ? [{ id: 'portal', name: '登录 Portal', description: '在浏览器中打开登录地址' }]
20
+ : [],
21
+ };
22
+ }
23
+ export class PortalAcpAgent {
24
+ client;
25
+ spaceId;
26
+ workbench;
27
+ baseUrl;
28
+ sessions = new Map();
29
+ constructor(client, spaceId, workbench, baseUrl = '') {
30
+ this.client = client;
31
+ this.spaceId = spaceId;
32
+ this.workbench = workbench;
33
+ this.baseUrl = baseUrl;
34
+ }
35
+ initialize() {
36
+ return portalInitialize();
37
+ }
38
+ newSession(params) {
39
+ const cwd = absoluteCwd(params.cwd);
40
+ const session = this.openSession(createSessionId(), cwd, '');
41
+ rememberSession(this.record(session));
42
+ return { sessionId: session.id, configOptions: this.options(session) };
43
+ }
44
+ async loadSession(params, acp) {
45
+ const saved = readSessions().find((session) => session.id === params.sessionId && session.baseUrl === portalBaseUrl(this.baseUrl));
46
+ if (!saved)
47
+ throw RequestError.sessionNotFound(params.sessionId);
48
+ const session = this.openSession(saved.id, absoluteCwd(params.cwd), saved.title, saved);
49
+ rememberSession(this.record(session));
50
+ await replayHistory({
51
+ client: this.client,
52
+ spaceId: this.spaceId,
53
+ sessionId: session.id,
54
+ acp,
55
+ });
56
+ return { configOptions: this.options(session) };
57
+ }
58
+ listSessions(params) {
59
+ const cwd = params.cwd ? path.resolve(params.cwd) : '';
60
+ const origin = portalBaseUrl(this.baseUrl);
61
+ const sessions = readSessions()
62
+ .filter((session) => session.baseUrl === origin)
63
+ .filter((session) => !cwd || session.cwd === cwd)
64
+ .toReversed()
65
+ .map((session) => ({
66
+ sessionId: session.id,
67
+ cwd: session.cwd,
68
+ title: session.title || null,
69
+ }));
70
+ return { sessions };
71
+ }
72
+ setConfig(params) {
73
+ const session = this.requireSession(params.sessionId);
74
+ if (typeof params.value !== 'string') {
75
+ throw RequestError.invalidParams({ configId: params.configId });
76
+ }
77
+ const value = params.value;
78
+ if (params.configId === 'model') {
79
+ const model = this.workbench.models.find((item) => item.id === value);
80
+ if (!model)
81
+ throw RequestError.invalidParams({ value });
82
+ session.modelId = value;
83
+ // The new model may not accept the current level, so re-clamp it instead
84
+ // of sending an unsupported effort on the next turn.
85
+ if (!isReasoningEffort(model, session.reasoningEffort)) {
86
+ session.reasoningEffort = defaultReasoningEffort(model, this.workbench.defaultReasoningEffort);
87
+ }
88
+ }
89
+ else if (params.configId === 'reasoning') {
90
+ if (!isReasoningEffort(this.model(session), value)) {
91
+ throw RequestError.invalidParams({ value });
92
+ }
93
+ session.reasoningEffort = value;
94
+ }
95
+ else {
96
+ throw RequestError.invalidParams({ configId: params.configId });
97
+ }
98
+ rememberSession(this.record(session));
99
+ return { configOptions: this.options(session) };
100
+ }
101
+ async prompt(params, acp) {
102
+ const session = this.requireSession(params.sessionId);
103
+ session.abort?.abort();
104
+ const abort = new AbortController();
105
+ session.abort = abort;
106
+ try {
107
+ return await runAcpTurn({
108
+ session,
109
+ client: this.client,
110
+ spaceId: this.spaceId,
111
+ agentId: this.workbench.agentId,
112
+ models: this.workbench.models,
113
+ acp,
114
+ message: promptText(params.prompt),
115
+ signal: abort.signal,
116
+ });
117
+ }
118
+ catch (error) {
119
+ if (abort.signal.aborted)
120
+ return { stopReason: 'cancelled' };
121
+ throw error;
122
+ }
123
+ finally {
124
+ if (session.abort === abort)
125
+ session.abort = null;
126
+ }
127
+ }
128
+ cancel(sessionId) {
129
+ this.sessions.get(sessionId)?.abort?.abort();
130
+ }
131
+ openSession(id, cwd, title, saved) {
132
+ const existing = this.sessions.get(id);
133
+ if (existing) {
134
+ existing.cwd = cwd;
135
+ if (title)
136
+ existing.title = title;
137
+ return existing;
138
+ }
139
+ // A configuration persisted for this session wins over the defaults, but it
140
+ // can go stale (model offline, effort no longer supported), so keep it only
141
+ // if the model still accepts it.
142
+ const savedModelId = saved?.modelId ?? '';
143
+ const savedEffort = saved?.reasoningEffort ?? '';
144
+ const model = this.workbench.models.some((item) => item.id === savedModelId)
145
+ ? this.workbench.models.find((item) => item.id === savedModelId)
146
+ : pickModel(this.workbench.models, this.workbench.defaultModelId, process.env.PORTAL_RUNTIME_MODEL);
147
+ const session = {
148
+ id,
149
+ cwd,
150
+ baseUrl: portalBaseUrl(this.baseUrl),
151
+ title,
152
+ modelId: model?.id ?? this.workbench.defaultModelId,
153
+ reasoningEffort: isReasoningEffort(model, savedEffort)
154
+ ? savedEffort
155
+ : defaultReasoningEffort(model, process.env.PORTAL_REASONING_EFFORT || this.workbench.defaultReasoningEffort),
156
+ sentThoughts: new Map(),
157
+ abort: null,
158
+ };
159
+ this.sessions.set(id, session);
160
+ return session;
161
+ }
162
+ record(session) {
163
+ return {
164
+ id: session.id,
165
+ cwd: session.cwd,
166
+ baseUrl: session.baseUrl,
167
+ title: session.title,
168
+ modelId: session.modelId,
169
+ reasoningEffort: session.reasoningEffort,
170
+ };
171
+ }
172
+ requireSession(sessionId) {
173
+ const session = this.sessions.get(sessionId);
174
+ if (!session)
175
+ throw RequestError.sessionNotFound(sessionId);
176
+ return session;
177
+ }
178
+ model(session) {
179
+ return this.workbench.models.find((item) => item.id === session.modelId);
180
+ }
181
+ options(session) {
182
+ return sessionConfigOptions({
183
+ models: this.workbench.models,
184
+ modelId: session.modelId,
185
+ reasoningEffort: session.reasoningEffort,
186
+ });
187
+ }
188
+ }
189
+ function absoluteCwd(cwd) {
190
+ if (!path.isAbsolute(cwd)) {
191
+ throw RequestError.invalidParams({ cwd }, 'cwd must be an absolute path');
192
+ }
193
+ return path.resolve(cwd);
194
+ }
195
+ //# sourceMappingURL=agent.js.map
@@ -0,0 +1,15 @@
1
+ import { type AgentContext } from '@agentclientprotocol/sdk';
2
+ import type { PortalClient } from '../portal/client.js';
3
+ export interface HistoryLine {
4
+ id: string;
5
+ role: 'user' | 'assistant';
6
+ text: string;
7
+ }
8
+ export declare function historyLines(records: unknown): HistoryLine[];
9
+ export declare function replayHistory(input: {
10
+ client: PortalClient;
11
+ spaceId: string;
12
+ sessionId: string;
13
+ acp: AgentContext;
14
+ }): Promise<void>;
15
+ //# sourceMappingURL=history.d.ts.map
@@ -0,0 +1,41 @@
1
+ import { methods } from '@agentclientprotocol/sdk';
2
+ export function historyLines(records) {
3
+ if (!Array.isArray(records))
4
+ return [];
5
+ const lines = [];
6
+ for (const record of records) {
7
+ const item = record;
8
+ const role = item.Role === 'user' ? 'user' : item.Role === 'assistant' ? 'assistant' : '';
9
+ if (!role || !Array.isArray(item.Messages))
10
+ continue;
11
+ const text = item.Messages.flatMap((message) => readMessageText(message, role)).join('\n');
12
+ if (!text)
13
+ continue;
14
+ lines.push({ id: String(item.RecordId || lines.length), role, text });
15
+ }
16
+ return lines;
17
+ }
18
+ export async function replayHistory(input) {
19
+ const body = await input.client.postJson(`/api/spaces/${encodeURIComponent(input.spaceId)}/chat/history`, { ConversationId: input.sessionId }, { 'X-Portal-Source': 'chat' });
20
+ for (const line of historyLines(body.Records)) {
21
+ await input.acp.notify(methods.client.session.update, {
22
+ sessionId: input.sessionId,
23
+ update: {
24
+ sessionUpdate: line.role === 'user' ? 'user_message_chunk' : 'agent_message_chunk',
25
+ messageId: line.id,
26
+ content: { type: 'text', text: line.text },
27
+ },
28
+ });
29
+ }
30
+ }
31
+ function readMessageText(message, role) {
32
+ const item = message;
33
+ const expected = role === 'user' ? 'question' : 'reply';
34
+ if (item.Type !== expected || !Array.isArray(item.Contents))
35
+ return [];
36
+ return item.Contents.flatMap((content) => {
37
+ const block = content;
38
+ return block.Type === 'text' && typeof block.Text === 'string' ? [block.Text] : [];
39
+ });
40
+ }
41
+ //# sourceMappingURL=history.js.map
@@ -0,0 +1,9 @@
1
+ import type { SessionConfigOption } from '@agentclientprotocol/sdk';
2
+ import { type RuntimeModel } from '../portal/target.js';
3
+ export declare function modelLabel(model: RuntimeModel): string;
4
+ export declare function sessionConfigOptions(input: {
5
+ models: RuntimeModel[];
6
+ modelId: string;
7
+ reasoningEffort: string;
8
+ }): SessionConfigOption[];
9
+ //# sourceMappingURL=options.d.ts.map
@@ -0,0 +1,45 @@
1
+ import { reasoningEfforts } from '../portal/target.js';
2
+ const REASONING = [
3
+ ['none', '关闭'],
4
+ ['minimal', '最低'],
5
+ ['low', '低'],
6
+ ['medium', '中'],
7
+ ['high', '高'],
8
+ ['xhigh', '最高'],
9
+ ];
10
+ export function modelLabel(model) {
11
+ return model.label || model.name || model.modelName || model.id;
12
+ }
13
+ export function sessionConfigOptions(input) {
14
+ const selected = input.models.find((model) => model.id === input.modelId);
15
+ const efforts = reasoningEfforts(selected);
16
+ const modelOption = {
17
+ id: 'model',
18
+ name: '模型',
19
+ category: 'model',
20
+ type: 'select',
21
+ currentValue: input.modelId,
22
+ options: input.models.map((model) => ({
23
+ value: model.id,
24
+ name: modelLabel(model),
25
+ })),
26
+ };
27
+ // Nothing to choose: the model either cannot think or has a single level.
28
+ if (efforts.length <= 1)
29
+ return [modelOption];
30
+ return [
31
+ modelOption,
32
+ {
33
+ id: 'reasoning',
34
+ name: '思考强度',
35
+ category: 'thought_level',
36
+ type: 'select',
37
+ currentValue: input.reasoningEffort,
38
+ options: efforts.map((value) => ({
39
+ value,
40
+ name: REASONING.find(([effort]) => effort === value)?.[1] ?? value,
41
+ })),
42
+ },
43
+ ];
44
+ }
45
+ //# sourceMappingURL=options.js.map
@@ -0,0 +1,3 @@
1
+ import type { ContentBlock } from '@agentclientprotocol/sdk';
2
+ export declare function promptText(blocks: ContentBlock[]): string;
3
+ //# sourceMappingURL=prompt.d.ts.map
@@ -0,0 +1,10 @@
1
+ export function promptText(blocks) {
2
+ return blocks.map((block) => {
3
+ if (block.type === 'text')
4
+ return block.text;
5
+ if (block.type === 'resource_link')
6
+ return block.uri;
7
+ return '';
8
+ }).filter(Boolean).join('\n');
9
+ }
10
+ //# sourceMappingURL=prompt.js.map
@@ -0,0 +1,2 @@
1
+ export declare function serveAcp(): Promise<void>;
2
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1,96 @@
1
+ import { Readable, Writable } from 'node:stream';
2
+ import * as acp from '@agentclientprotocol/sdk';
3
+ import { writeAuthFile } from '../auth/loadAuth.js';
4
+ import { browserLoginRequired, connectAuth } from '../auth/login.js';
5
+ import { PortalClient } from '../portal/client.js';
6
+ import { loadWorkbench } from '../portal/target.js';
7
+ import { PortalAcpAgent, portalInitialize } from './agent.js';
8
+ export async function serveAcp() {
9
+ let started;
10
+ let canShowLoginUrl = false;
11
+ const stream = acp.ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin));
12
+ const start = (interactive, request) => {
13
+ const run = createAgent(interactive, request, canShowLoginUrl);
14
+ started = run;
15
+ run.catch(() => {
16
+ if (started === run)
17
+ started = undefined;
18
+ });
19
+ return run;
20
+ };
21
+ const requireAgent = () => {
22
+ if (started)
23
+ return started;
24
+ if (browserLoginRequired())
25
+ return Promise.reject(acp.RequestError.authRequired(undefined, '请先登录 Portal'));
26
+ return start(false);
27
+ };
28
+ acp.agent({ name: 'portal' })
29
+ .onRequest(acp.methods.agent.initialize, (ctx) => {
30
+ canShowLoginUrl = ctx.params.clientCapabilities?.elicitation?.url != null;
31
+ return portalInitialize(browserLoginRequired());
32
+ })
33
+ .onRequest(acp.methods.agent.authenticate, async (ctx) => {
34
+ try {
35
+ await start(true, ctx.client);
36
+ }
37
+ catch (error) {
38
+ if (error instanceof acp.RequestError)
39
+ throw error;
40
+ const message = error instanceof Error ? error.message : String(error);
41
+ console.error(message);
42
+ throw new acp.RequestError(-32603, message);
43
+ }
44
+ return {};
45
+ })
46
+ .onRequest(acp.methods.agent.logout, async () => {
47
+ writeAuthFile({ apiKey: '', accessToken: '', refreshToken: '', expiresAt: 0 });
48
+ started = undefined;
49
+ return {};
50
+ })
51
+ .onRequest(acp.methods.agent.session.new, async (ctx) => (await requireAgent()).newSession(ctx.params))
52
+ .onRequest(acp.methods.agent.session.load, async (ctx) => (await requireAgent()).loadSession(ctx.params, ctx.client))
53
+ .onRequest(acp.methods.agent.session.list, async (ctx) => (await requireAgent()).listSessions(ctx.params))
54
+ .onRequest(acp.methods.agent.session.setConfigOption, async (ctx) => (await requireAgent()).setConfig(ctx.params))
55
+ .onRequest(acp.methods.agent.session.prompt, async (ctx) => (await requireAgent()).prompt(ctx.params, ctx.client))
56
+ .onNotification(acp.methods.agent.session.cancel, (ctx) => {
57
+ void requireAgent().then((agent) => agent.cancel(ctx.params.sessionId));
58
+ })
59
+ .connect(stream);
60
+ }
61
+ const LOGIN_URL_ID = 'portal-login';
62
+ async function createAgent(interactive, request, canShowLoginUrl = false) {
63
+ let showedLoginUrl = false;
64
+ try {
65
+ const auth = await connectAuth({
66
+ interactive,
67
+ showUrl: canShowLoginUrl && request?.requestId !== undefined
68
+ ? (url) => {
69
+ showedLoginUrl = true;
70
+ return request.request(acp.methods.client.elicitation.create, {
71
+ mode: 'url',
72
+ elicitationId: LOGIN_URL_ID,
73
+ url,
74
+ message: '请在浏览器里登录 Portal,并选择要授权的空间。',
75
+ requestId: request.requestId,
76
+ });
77
+ }
78
+ : undefined,
79
+ });
80
+ if (!auth)
81
+ throw acp.RequestError.authRequired(undefined, '请先登录 Portal');
82
+ const client = new PortalClient(auth);
83
+ const workbench = await loadWorkbench(client, auth.spaceId);
84
+ return new PortalAcpAgent(client, auth.spaceId, workbench, auth.baseUrl);
85
+ }
86
+ finally {
87
+ if (showedLoginUrl && request) {
88
+ await request.notify(acp.methods.client.elicitation.complete, {
89
+ elicitationId: LOGIN_URL_ID,
90
+ }).catch((error) => {
91
+ console.error(error instanceof Error ? error.message : String(error));
92
+ });
93
+ }
94
+ }
95
+ }
96
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1,12 @@
1
+ export interface AcpSession {
2
+ id: string;
3
+ cwd: string;
4
+ baseUrl: string;
5
+ title: string;
6
+ modelId: string;
7
+ reasoningEffort: string;
8
+ /** Reasoning text already sent to the client, keyed by thought messageId. */
9
+ sentThoughts: Map<string, string>;
10
+ abort: AbortController | null;
11
+ }
12
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1,15 @@
1
+ import { type AgentContext, type PromptResponse } from '@agentclientprotocol/sdk';
2
+ import type { PortalClient } from '../portal/client.js';
3
+ import type { RuntimeModel } from '../portal/target.js';
4
+ import type { AcpSession } from './session.js';
5
+ export declare function runAcpTurn(input: {
6
+ session: AcpSession;
7
+ client: PortalClient;
8
+ spaceId: string;
9
+ agentId: string;
10
+ acp: AgentContext;
11
+ models: RuntimeModel[];
12
+ message: string;
13
+ signal: AbortSignal;
14
+ }): Promise<PromptResponse>;
15
+ //# sourceMappingURL=turn.d.ts.map
@@ -0,0 +1,158 @@
1
+ import path from 'node:path';
2
+ import { methods } from '@agentclientprotocol/sdk';
3
+ import { rememberSession } from '../cli/sessions.js';
4
+ import { chatBody, QuestionDeclined, runChat } from '../portal/chat.js';
5
+ import { runLocalTool } from '../tools/local.js';
6
+ export async function runAcpTurn(input) {
7
+ const result = await runChat({
8
+ message: input.message,
9
+ cwd: input.session.cwd,
10
+ ask: (question) => askUser(input, question),
11
+ replyQuestion: (question, reply) => input.client.replyQuestion({
12
+ spaceId: input.spaceId,
13
+ agentId: input.agentId,
14
+ interactionId: question.interactionId,
15
+ expectedVersion: question.version,
16
+ answers: reply.answers,
17
+ rejected: reply.rejected,
18
+ signal: input.signal,
19
+ }),
20
+ onText: (text) => update(input, {
21
+ sessionUpdate: 'agent_message_chunk',
22
+ content: { type: 'text', text },
23
+ }),
24
+ // ACP v2 chunks (agent_thought_chunk / agent_message_chunk) are append-only:
25
+ // the client concatenates them per messageId. Portal re-sends the whole
26
+ // reasoning block on every chunk, so each thought update must add only the
27
+ // part the client has not seen. sse.ts already drops repeats; the unseen
28
+ // suffix is computed here and sent at most once per messageId.
29
+ onThought: (thought) => update(input, {
30
+ sessionUpdate: 'agent_thought_chunk',
31
+ messageId: thought.id,
32
+ content: { type: 'text', text: unseenThoughtSuffix(input, thought) },
33
+ }),
34
+ onTitle: async (title) => {
35
+ input.session.title = title;
36
+ rememberSession({
37
+ id: input.session.id,
38
+ cwd: input.session.cwd,
39
+ baseUrl: input.session.baseUrl,
40
+ title,
41
+ modelId: input.session.modelId,
42
+ reasoningEffort: input.session.reasoningEffort,
43
+ });
44
+ await update(input, { sessionUpdate: 'session_info_update', title });
45
+ },
46
+ onTool: (call) => reportTool(input, call),
47
+ openStream: (turn) => input.client.streamChat({
48
+ spaceId: input.spaceId,
49
+ agentId: input.agentId,
50
+ modelId: input.session.modelId,
51
+ reasoningEffort: input.session.reasoningEffort,
52
+ body: chatBody(input.session.id, turn),
53
+ signal: input.signal,
54
+ }),
55
+ });
56
+ // Report the context window once per turn, after the response completed. The
57
+ // limit falls back to the model's contextLength when the backend omits it.
58
+ if (result.contextUsage) {
59
+ await reportContextUsage(input, result.contextUsage.usedTokens, result.contextUsage.limitTokens);
60
+ }
61
+ return { stopReason: input.signal.aborted ? 'cancelled' : 'end_turn' };
62
+ }
63
+ async function reportContextUsage(input, used, reportedLimit) {
64
+ if (!Number.isFinite(used) || used < 0)
65
+ return;
66
+ const limit = reportedLimit
67
+ ?? contextLengthOf(input.models, input.session.modelId);
68
+ // Without a known window there is nothing meaningful to draw, so stay silent
69
+ // instead of reporting a usage that no ring can show.
70
+ if (!limit || !Number.isFinite(limit) || limit <= 0)
71
+ return;
72
+ await update(input, {
73
+ sessionUpdate: 'usage_update',
74
+ used: Math.min(used, limit),
75
+ size: limit,
76
+ });
77
+ }
78
+ function contextLengthOf(models, modelId) {
79
+ const length = models.find((model) => model.id === modelId)?.contextLength;
80
+ return typeof length === 'number' && Number.isFinite(length) && length > 0 ? length : undefined;
81
+ }
82
+ // The first chunk of a thought message must carry its text from the start; every
83
+ // later chunk only carries what the client has not received yet.
84
+ function unseenThoughtSuffix(input, thought) {
85
+ const sent = input.session.sentThoughts.get(thought.id) ?? '';
86
+ const suffix = thought.text.startsWith(sent) ? thought.text.slice(sent.length) : thought.text;
87
+ input.session.sentThoughts.set(thought.id, thought.text);
88
+ return suffix;
89
+ }
90
+ async function askUser(input, question) {
91
+ const answers = [];
92
+ for (const [index, item] of question.questions.entries()) {
93
+ const response = await input.acp.request(methods.client.session.requestPermission, {
94
+ sessionId: input.session.id,
95
+ toolCall: {
96
+ toolCallId: `${question.interactionId}-${index}`,
97
+ title: item.question || item.header || '需要你回答',
98
+ kind: 'other',
99
+ status: 'pending',
100
+ rawInput: { question: item.question, options: item.options },
101
+ },
102
+ options: permissionOptions(item),
103
+ }, {
104
+ cancellationSignal: input.signal,
105
+ stopWaitingOnCancel: true,
106
+ });
107
+ if (response.outcome.outcome !== 'selected')
108
+ throw new QuestionDeclined();
109
+ const selected = item.options[Number(response.outcome.optionId)];
110
+ answers.push([selected?.label ?? response.outcome.optionId]);
111
+ }
112
+ return answers;
113
+ }
114
+ function permissionOptions(item) {
115
+ return item.options.map((option, index) => ({
116
+ optionId: String(index),
117
+ name: option.description ? `${option.label} — ${option.description}` : option.label,
118
+ kind: 'allow_once',
119
+ }));
120
+ }
121
+ async function reportTool(input, call) {
122
+ const filePath = typeof call.arguments.file_path === 'string' ? call.arguments.file_path : '';
123
+ await update(input, {
124
+ sessionUpdate: 'tool_call',
125
+ toolCallId: call.callId,
126
+ title: String(call.arguments.command || filePath || call.name),
127
+ name: call.name,
128
+ kind: toolKind(call.name),
129
+ status: 'in_progress',
130
+ rawInput: call.arguments,
131
+ ...(filePath ? { locations: [{ path: path.resolve(input.session.cwd, filePath) }] } : {}),
132
+ });
133
+ const output = await runLocalTool(input.session.cwd, call);
134
+ await update(input, {
135
+ sessionUpdate: 'tool_call_update',
136
+ toolCallId: call.callId,
137
+ status: 'completed',
138
+ rawOutput: output,
139
+ content: [{ type: 'content', content: { type: 'text', text: output } }],
140
+ });
141
+ return output;
142
+ }
143
+ function toolKind(name) {
144
+ if (name === 'exec')
145
+ return 'execute';
146
+ if (name === 'read')
147
+ return 'read';
148
+ if (name === 'edit')
149
+ return 'edit';
150
+ return 'other';
151
+ }
152
+ function update(input, sessionUpdate) {
153
+ return input.acp.notify(methods.client.session.update, {
154
+ sessionId: input.session.id,
155
+ update: sessionUpdate,
156
+ });
157
+ }
158
+ //# sourceMappingURL=turn.js.map
@@ -0,0 +1,22 @@
1
+ export interface PortalAuth {
2
+ baseUrl: string;
3
+ token: string;
4
+ spaceId: string;
5
+ /** Replace token after the server rejects it. Returns the new access token. */
6
+ renew?: () => Promise<string>;
7
+ }
8
+ /** What ~/.portal/auth.json stores. Extra keys the user added are kept. */
9
+ export interface SavedAuth {
10
+ baseUrl: string;
11
+ apiKey: string;
12
+ clientId: string;
13
+ resource: string;
14
+ accessToken: string;
15
+ refreshToken: string;
16
+ expiresAt: number;
17
+ }
18
+ export declare function authFile(): string;
19
+ export declare function readAuthFile(): SavedAuth | undefined;
20
+ export declare function writeAuthFile(patch: Partial<SavedAuth>, remove?: string[]): void;
21
+ export declare function origin(value: string | undefined): string;
22
+ //# sourceMappingURL=loadAuth.d.ts.map