@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.
- package/dist/acp/agent.d.ts +25 -0
- package/dist/acp/agent.js +195 -0
- package/dist/acp/history.d.ts +15 -0
- package/dist/acp/history.js +41 -0
- package/dist/acp/options.d.ts +9 -0
- package/dist/acp/options.js +45 -0
- package/dist/acp/prompt.d.ts +3 -0
- package/dist/acp/prompt.js +10 -0
- package/dist/acp/server.d.ts +2 -0
- package/dist/acp/server.js +96 -0
- package/dist/acp/session.d.ts +12 -0
- package/dist/acp/session.js +2 -0
- package/dist/acp/turn.d.ts +15 -0
- package/dist/acp/turn.js +158 -0
- package/dist/auth/loadAuth.d.ts +22 -0
- package/dist/auth/loadAuth.js +54 -0
- package/dist/auth/login.d.ts +28 -0
- package/dist/auth/login.js +339 -0
- package/dist/bin.d.ts +3 -0
- package/dist/bin.js +24 -0
- package/dist/cli/ask.d.ts +3 -0
- package/dist/cli/ask.js +30 -0
- package/dist/cli/chat.d.ts +5 -0
- package/dist/cli/chat.js +48 -0
- package/dist/cli/session.d.ts +2 -0
- package/dist/cli/session.js +6 -0
- package/dist/cli/sessions.d.ts +20 -0
- package/dist/cli/sessions.js +56 -0
- package/dist/portal/callerTools.d.ts +68 -0
- package/dist/portal/callerTools.js +50 -0
- package/dist/portal/chat.d.ts +23 -0
- package/dist/portal/chat.js +73 -0
- package/dist/portal/client.d.ts +29 -0
- package/dist/portal/client.js +98 -0
- package/dist/portal/headers.d.ts +3 -0
- package/dist/portal/headers.js +5 -0
- package/dist/portal/sse.d.ts +9 -0
- package/dist/portal/sse.js +219 -0
- package/dist/portal/sseLog.d.ts +4 -0
- package/dist/portal/sseLog.js +47 -0
- package/dist/portal/target.d.ts +40 -0
- package/dist/portal/target.js +72 -0
- package/dist/portal/types.d.ts +53 -0
- package/dist/portal/types.js +2 -0
- package/dist/tools/local.d.ts +3 -0
- package/dist/tools/local.js +122 -0
- package/package.json +36 -3
- package/README.md +0 -3
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
export declare const TOOL_GUIDANCE: string;
|
|
2
|
+
export declare const CALLER_TOOLS: ({
|
|
3
|
+
Name: string;
|
|
4
|
+
Description: string;
|
|
5
|
+
InputSchema: {
|
|
6
|
+
type: string;
|
|
7
|
+
properties: {
|
|
8
|
+
command: {
|
|
9
|
+
type: string;
|
|
10
|
+
description: string;
|
|
11
|
+
};
|
|
12
|
+
file_path?: undefined;
|
|
13
|
+
offset?: undefined;
|
|
14
|
+
limit?: undefined;
|
|
15
|
+
old_string?: undefined;
|
|
16
|
+
new_string?: undefined;
|
|
17
|
+
replace_all?: undefined;
|
|
18
|
+
};
|
|
19
|
+
required: string[];
|
|
20
|
+
};
|
|
21
|
+
} | {
|
|
22
|
+
Name: string;
|
|
23
|
+
Description: string;
|
|
24
|
+
InputSchema: {
|
|
25
|
+
type: string;
|
|
26
|
+
properties: {
|
|
27
|
+
file_path: {
|
|
28
|
+
type: string;
|
|
29
|
+
};
|
|
30
|
+
offset: {
|
|
31
|
+
type: string;
|
|
32
|
+
};
|
|
33
|
+
limit: {
|
|
34
|
+
type: string;
|
|
35
|
+
};
|
|
36
|
+
command?: undefined;
|
|
37
|
+
old_string?: undefined;
|
|
38
|
+
new_string?: undefined;
|
|
39
|
+
replace_all?: undefined;
|
|
40
|
+
};
|
|
41
|
+
required: string[];
|
|
42
|
+
};
|
|
43
|
+
} | {
|
|
44
|
+
Name: string;
|
|
45
|
+
Description: string;
|
|
46
|
+
InputSchema: {
|
|
47
|
+
type: string;
|
|
48
|
+
properties: {
|
|
49
|
+
file_path: {
|
|
50
|
+
type: string;
|
|
51
|
+
};
|
|
52
|
+
old_string: {
|
|
53
|
+
type: string;
|
|
54
|
+
};
|
|
55
|
+
new_string: {
|
|
56
|
+
type: string;
|
|
57
|
+
};
|
|
58
|
+
replace_all: {
|
|
59
|
+
type: string;
|
|
60
|
+
};
|
|
61
|
+
command?: undefined;
|
|
62
|
+
offset?: undefined;
|
|
63
|
+
limit?: undefined;
|
|
64
|
+
};
|
|
65
|
+
required: string[];
|
|
66
|
+
};
|
|
67
|
+
})[];
|
|
68
|
+
//# sourceMappingURL=callerTools.d.ts.map
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export const TOOL_GUIDANCE = [
|
|
2
|
+
'当前执行环境是调用方启动时所在的工作目录,命令和文件都在这台机器上,不在 Portal 沙箱里。',
|
|
3
|
+
'用户说当前项目、当前文件夹,指的都是这个执行环境。',
|
|
4
|
+
'在当前执行环境里,跑命令用 exec,读文件用 read,改文件用 edit。',
|
|
5
|
+
'改已有文件前先 read。edit 按原文逐字替换;要插入时把插入点前后的原文放进 old_string,',
|
|
6
|
+
'new_string 保留这段原文并加上新内容。new_string 为空是删除。',
|
|
7
|
+
'project_storage 只放用户要下载的最终结果,不要用它读写当前执行环境里的代码。',
|
|
8
|
+
].join('');
|
|
9
|
+
const READ_LINE_LIMIT = 2000;
|
|
10
|
+
export const CALLER_TOOLS = [
|
|
11
|
+
{
|
|
12
|
+
Name: 'exec',
|
|
13
|
+
Description: '在本地 bash 里执行一条命令,返回 stdout、stderr 和退出码。',
|
|
14
|
+
InputSchema: {
|
|
15
|
+
type: 'object',
|
|
16
|
+
properties: {
|
|
17
|
+
command: { type: 'string', description: '要执行的 shell 命令' },
|
|
18
|
+
},
|
|
19
|
+
required: ['command'],
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
Name: 'read',
|
|
24
|
+
Description: `读取本地 UTF-8 文本文件。offset 从 1 开始,limit 最多 ${READ_LINE_LIMIT} 行。`,
|
|
25
|
+
InputSchema: {
|
|
26
|
+
type: 'object',
|
|
27
|
+
properties: {
|
|
28
|
+
file_path: { type: 'string' },
|
|
29
|
+
offset: { type: 'integer' },
|
|
30
|
+
limit: { type: 'integer' },
|
|
31
|
+
},
|
|
32
|
+
required: ['file_path'],
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
Name: 'edit',
|
|
37
|
+
Description: '按原文逐字修改一个已有的 UTF-8 文本文件。old_string 必须逐字匹配。',
|
|
38
|
+
InputSchema: {
|
|
39
|
+
type: 'object',
|
|
40
|
+
properties: {
|
|
41
|
+
file_path: { type: 'string' },
|
|
42
|
+
old_string: { type: 'string' },
|
|
43
|
+
new_string: { type: 'string' },
|
|
44
|
+
replace_all: { type: 'boolean' },
|
|
45
|
+
},
|
|
46
|
+
required: ['file_path', 'old_string', 'new_string'],
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
];
|
|
50
|
+
//# sourceMappingURL=callerTools.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ChatTurn, ContextUsage, ThoughtBlock, ToolCall, UserQuestion } from './types.js';
|
|
2
|
+
export declare class QuestionDeclined extends Error {
|
|
3
|
+
}
|
|
4
|
+
export declare function chatBody(sessionId: string, turn: ChatTurn): Record<string, unknown>;
|
|
5
|
+
export declare function runChat(input: {
|
|
6
|
+
message: string;
|
|
7
|
+
cwd: string;
|
|
8
|
+
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>;
|
|
14
|
+
onText?: (text: string) => Promise<void>;
|
|
15
|
+
onTitle?: (title: string) => Promise<void>;
|
|
16
|
+
onThought?: (thought: ThoughtBlock) => Promise<void>;
|
|
17
|
+
onTool?: (call: ToolCall) => Promise<string>;
|
|
18
|
+
}): Promise<{
|
|
19
|
+
text: string;
|
|
20
|
+
sessionTitle: string;
|
|
21
|
+
contextUsage?: ContextUsage;
|
|
22
|
+
}>;
|
|
23
|
+
//# sourceMappingURL=chat.d.ts.map
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { runLocalTool } from '../tools/local.js';
|
|
3
|
+
import { CALLER_TOOLS, TOOL_GUIDANCE } from './callerTools.js';
|
|
4
|
+
import { readChatStream } from './sse.js';
|
|
5
|
+
export class QuestionDeclined extends Error {
|
|
6
|
+
}
|
|
7
|
+
export function chatBody(sessionId, turn) {
|
|
8
|
+
return {
|
|
9
|
+
RequestId: randomBytes(16).toString('hex'),
|
|
10
|
+
ConversationId: sessionId,
|
|
11
|
+
Contents: turn.contents,
|
|
12
|
+
Tools: CALLER_TOOLS,
|
|
13
|
+
ToolGuidance: TOOL_GUIDANCE,
|
|
14
|
+
Incremental: true,
|
|
15
|
+
Stream: 'enable',
|
|
16
|
+
...(turn.previousResponseId ? { PreviousResponseId: turn.previousResponseId } : {}),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
// One HTTP stream is one model step. Tool calls come back here, run on this
|
|
20
|
+
// machine, and the outputs resume the same assistant reply.
|
|
21
|
+
export async function runChat(input) {
|
|
22
|
+
let contents = [{ Type: 'text', Text: input.message }];
|
|
23
|
+
let previousResponseId = '';
|
|
24
|
+
let text = '';
|
|
25
|
+
let sessionTitle = '';
|
|
26
|
+
let contextUsage;
|
|
27
|
+
let response = input.openStream({ contents, previousResponseId });
|
|
28
|
+
for (;;) {
|
|
29
|
+
const segment = await readChatStream(await response, {
|
|
30
|
+
onText: input.onText,
|
|
31
|
+
onThought: input.onThought,
|
|
32
|
+
onTitle: async (title) => {
|
|
33
|
+
sessionTitle = title;
|
|
34
|
+
await input.onTitle?.(title);
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
if (segment.errors.length > 0)
|
|
38
|
+
throw new Error(segment.errors.at(-1));
|
|
39
|
+
text += segment.text;
|
|
40
|
+
// Keep the latest reported window usage; a turn can span several streams
|
|
41
|
+
// when local tools run in between.
|
|
42
|
+
contextUsage = segment.contextUsage ?? contextUsage;
|
|
43
|
+
if (segment.question) {
|
|
44
|
+
response = replyToQuestion(input, segment.question);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (segment.completed || segment.calls.length === 0) {
|
|
48
|
+
return { text, sessionTitle, ...(contextUsage ? { contextUsage } : {}) };
|
|
49
|
+
}
|
|
50
|
+
contents = [];
|
|
51
|
+
for (const call of segment.calls) {
|
|
52
|
+
contents.push({
|
|
53
|
+
Type: 'function_call_output',
|
|
54
|
+
CallId: call.callId,
|
|
55
|
+
Output: input.onTool ? await input.onTool(call) : await runLocalTool(input.cwd, call),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
previousResponseId = segment.recordId;
|
|
59
|
+
response = input.openStream({ contents, previousResponseId });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
async function replyToQuestion(input, question) {
|
|
63
|
+
try {
|
|
64
|
+
const answers = await input.ask(question);
|
|
65
|
+
return input.replyQuestion(question, { answers });
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (!(error instanceof QuestionDeclined))
|
|
69
|
+
throw error;
|
|
70
|
+
return input.replyQuestion(question, { rejected: true });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
//# sourceMappingURL=chat.js.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { PortalAuth } from '../auth/loadAuth.js';
|
|
2
|
+
export declare class PortalClient {
|
|
3
|
+
private readonly auth;
|
|
4
|
+
private renewing;
|
|
5
|
+
constructor(auth: PortalAuth);
|
|
6
|
+
getJson<T>(pathname: string): Promise<T>;
|
|
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
|
+
streamChat(input: {
|
|
18
|
+
spaceId: string;
|
|
19
|
+
agentId: string;
|
|
20
|
+
modelId: string;
|
|
21
|
+
reasoningEffort: string;
|
|
22
|
+
body: unknown;
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
}): Promise<Response>;
|
|
25
|
+
private post;
|
|
26
|
+
private call;
|
|
27
|
+
private renew;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { portalHeaders } from './headers.js';
|
|
3
|
+
import { loggedSseBody, logSse } from './sseLog.js';
|
|
4
|
+
export class PortalClient {
|
|
5
|
+
auth;
|
|
6
|
+
renewing = null;
|
|
7
|
+
constructor(auth) {
|
|
8
|
+
this.auth = auth;
|
|
9
|
+
}
|
|
10
|
+
async getJson(pathname) {
|
|
11
|
+
const response = await this.call(new URL(pathname, this.auth.baseUrl), {
|
|
12
|
+
headers: { Accept: 'application/json' },
|
|
13
|
+
});
|
|
14
|
+
if (!response.ok) {
|
|
15
|
+
throw new Error(`GET ${pathname} failed with HTTP ${response.status}: ${await response.text()}`);
|
|
16
|
+
}
|
|
17
|
+
const body = await response.json();
|
|
18
|
+
return body.data ?? body;
|
|
19
|
+
}
|
|
20
|
+
async postJson(pathname, body, headers = {}) {
|
|
21
|
+
const response = await this.call(new URL(pathname, this.auth.baseUrl), {
|
|
22
|
+
method: 'POST',
|
|
23
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/json', ...headers },
|
|
24
|
+
body: JSON.stringify(body),
|
|
25
|
+
});
|
|
26
|
+
if (!response.ok) {
|
|
27
|
+
throw new Error(`POST ${pathname} failed with HTTP ${response.status}: ${await response.text()}`);
|
|
28
|
+
}
|
|
29
|
+
const payload = await response.json();
|
|
30
|
+
return payload.data ?? payload;
|
|
31
|
+
}
|
|
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
|
+
streamChat(input) {
|
|
43
|
+
return this.post(`/api/spaces/${encodeURIComponent(input.spaceId)}/chat/stream`, input.body, {
|
|
44
|
+
Accept: 'text/event-stream',
|
|
45
|
+
'X-Portal-Agent-Id': input.agentId,
|
|
46
|
+
'X-Portal-Source': 'chat',
|
|
47
|
+
'X-Portal-Chat-Entry-Point': 'home',
|
|
48
|
+
'X-Portal-Runtime-Model-Id': input.modelId,
|
|
49
|
+
'X-Portal-Reasoning-Effort': input.reasoningEffort,
|
|
50
|
+
}, input.signal);
|
|
51
|
+
}
|
|
52
|
+
async post(pathname, body, headers, signal) {
|
|
53
|
+
const response = await this.call(new URL(pathname, this.auth.baseUrl), {
|
|
54
|
+
method: 'POST',
|
|
55
|
+
headers: { 'Content-Type': 'application/json', ...headers },
|
|
56
|
+
body: JSON.stringify(body),
|
|
57
|
+
signal,
|
|
58
|
+
});
|
|
59
|
+
const label = `${response.status} POST ${pathname}`;
|
|
60
|
+
if (!response.ok || !response.body) {
|
|
61
|
+
const text = await response.text();
|
|
62
|
+
logSse(label, text);
|
|
63
|
+
if (!response.ok)
|
|
64
|
+
throw new Error(`Portal chat failed with HTTP ${response.status}: ${text}`);
|
|
65
|
+
return response;
|
|
66
|
+
}
|
|
67
|
+
return new Response(loggedSseBody(label, response.body), {
|
|
68
|
+
status: response.status,
|
|
69
|
+
statusText: response.statusText,
|
|
70
|
+
headers: response.headers,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
async call(url, init) {
|
|
74
|
+
const send = () => fetch(url, {
|
|
75
|
+
...init,
|
|
76
|
+
headers: portalHeaders(url, {
|
|
77
|
+
...init.headers,
|
|
78
|
+
Authorization: `Bearer ${this.auth.token}`,
|
|
79
|
+
}),
|
|
80
|
+
});
|
|
81
|
+
const response = await send();
|
|
82
|
+
if (response.status !== 401 || !this.auth.renew)
|
|
83
|
+
return response;
|
|
84
|
+
await response.body?.cancel();
|
|
85
|
+
this.auth.token = await this.renew();
|
|
86
|
+
return send();
|
|
87
|
+
}
|
|
88
|
+
renew() {
|
|
89
|
+
const renew = this.auth.renew;
|
|
90
|
+
if (!renew)
|
|
91
|
+
return Promise.reject(new Error('登录已失效,请重新运行。'));
|
|
92
|
+
this.renewing ??= renew().finally(() => {
|
|
93
|
+
this.renewing = null;
|
|
94
|
+
});
|
|
95
|
+
return this.renewing;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { StreamSegment, ThoughtBlock } from './types.js';
|
|
2
|
+
interface StreamCallbacks {
|
|
3
|
+
onText?: (text: string) => Promise<void>;
|
|
4
|
+
onTitle?: (title: string) => Promise<void>;
|
|
5
|
+
onThought?: (thought: ThoughtBlock) => Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export declare function readChatStream(response: Response, callbacks?: StreamCallbacks): Promise<StreamSegment>;
|
|
8
|
+
export {};
|
|
9
|
+
//# sourceMappingURL=sse.d.ts.map
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
export async function readChatStream(response, callbacks = {}) {
|
|
2
|
+
if (!response.body)
|
|
3
|
+
throw new Error('Portal chat returned an empty stream');
|
|
4
|
+
const state = {
|
|
5
|
+
segment: {
|
|
6
|
+
text: '',
|
|
7
|
+
thoughts: [],
|
|
8
|
+
calls: [],
|
|
9
|
+
recordId: '',
|
|
10
|
+
completed: false,
|
|
11
|
+
errors: [],
|
|
12
|
+
sessionTitle: '',
|
|
13
|
+
},
|
|
14
|
+
callbacks,
|
|
15
|
+
emittedDelta: false,
|
|
16
|
+
thoughtTail: new Map(),
|
|
17
|
+
};
|
|
18
|
+
const reader = response.body.getReader();
|
|
19
|
+
const decoder = new TextDecoder();
|
|
20
|
+
let buffer = '';
|
|
21
|
+
for (;;) {
|
|
22
|
+
const { done, value } = await reader.read();
|
|
23
|
+
if (done)
|
|
24
|
+
break;
|
|
25
|
+
buffer += decoder.decode(value, { stream: true });
|
|
26
|
+
buffer = await consumeBlocks(buffer, state);
|
|
27
|
+
}
|
|
28
|
+
if (buffer.trim())
|
|
29
|
+
await consumeBlocks(`${buffer}\n\n`, state);
|
|
30
|
+
return state.segment;
|
|
31
|
+
}
|
|
32
|
+
async function consumeBlocks(buffer, state) {
|
|
33
|
+
const parts = buffer.split(/\r?\n\r?\n/);
|
|
34
|
+
const rest = parts.pop() ?? '';
|
|
35
|
+
// Await one block at a time so notification writes keep their SSE order.
|
|
36
|
+
for (const part of parts)
|
|
37
|
+
await applyBlock(part, state);
|
|
38
|
+
return rest;
|
|
39
|
+
}
|
|
40
|
+
async function applyBlock(block, state) {
|
|
41
|
+
const { segment, callbacks } = state;
|
|
42
|
+
let event = 'message';
|
|
43
|
+
const dataLines = [];
|
|
44
|
+
for (const line of block.split(/\r?\n/)) {
|
|
45
|
+
if (line.startsWith('event:'))
|
|
46
|
+
event = line.slice('event:'.length).trim();
|
|
47
|
+
else if (line.startsWith('data:'))
|
|
48
|
+
dataLines.push(line.slice('data:'.length).trim());
|
|
49
|
+
}
|
|
50
|
+
if (dataLines.length === 0 || dataLines.join('\n') === '[DONE]')
|
|
51
|
+
return;
|
|
52
|
+
const data = JSON.parse(dataLines.join('\n'));
|
|
53
|
+
if (event === 'text.delta') {
|
|
54
|
+
const delta = String(data.Text ?? '');
|
|
55
|
+
segment.text += delta;
|
|
56
|
+
state.emittedDelta = true;
|
|
57
|
+
await callbacks.onText?.(delta);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (event === 'error' || event === 'chat.error') {
|
|
61
|
+
segment.errors.push(JSON.stringify(data));
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (event === 'response.requires_action') {
|
|
65
|
+
const response = data.Response;
|
|
66
|
+
segment.recordId = response?.RecordId ?? segment.recordId;
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (event === 'response.completed') {
|
|
70
|
+
segment.completed = true;
|
|
71
|
+
// The completed response reports how much of the context window the turn
|
|
72
|
+
// used. It must not be derived from Usage: those counters accumulate over
|
|
73
|
+
// every step, so their total vastly exceeds the window.
|
|
74
|
+
segment.contextUsage = readContextUsage(data.Response) ?? segment.contextUsage;
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (event === 'message.added' || event === 'message.processing' || event === 'message.done') {
|
|
78
|
+
// Reasoning blocks only produce thought chunks; the rest of this function
|
|
79
|
+
// deals with reply/question/tool-call messages.
|
|
80
|
+
if (await applyThought(event, data, state))
|
|
81
|
+
return;
|
|
82
|
+
if (event === 'message.processing')
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (event === 'session.updated') {
|
|
86
|
+
const title = typeof data.title === 'string' ? data.title.trim() : '';
|
|
87
|
+
if (title) {
|
|
88
|
+
segment.sessionTitle = title;
|
|
89
|
+
await callbacks.onTitle?.(title);
|
|
90
|
+
}
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (event !== 'message.added' && event !== 'message.done')
|
|
94
|
+
return;
|
|
95
|
+
const message = data.Message;
|
|
96
|
+
const question = readQuestion(message?.ExtraInfo?.RuntimeInteraction);
|
|
97
|
+
if (question)
|
|
98
|
+
segment.question = question;
|
|
99
|
+
if (event !== 'message.done')
|
|
100
|
+
return;
|
|
101
|
+
if (message?.Type === 'reply') {
|
|
102
|
+
const texts = (message.Contents ?? [])
|
|
103
|
+
.filter((content) => content.Type === 'text' && content.Text)
|
|
104
|
+
.map((content) => String(content.Text));
|
|
105
|
+
if (texts.length > 0) {
|
|
106
|
+
const full = texts.join('\n');
|
|
107
|
+
// The final message repeats the whole reply. Keep it as the authoritative
|
|
108
|
+
// text for non-streaming callers, but only emit a chunk when the server
|
|
109
|
+
// never streamed deltas (e.g. ADP) — otherwise the client sees duplicates.
|
|
110
|
+
segment.text = full;
|
|
111
|
+
if (!state.emittedDelta)
|
|
112
|
+
await callbacks.onText?.(full);
|
|
113
|
+
}
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (message?.Type !== 'function_call')
|
|
117
|
+
return;
|
|
118
|
+
for (const content of message.Contents ?? []) {
|
|
119
|
+
if (content.Type !== 'function_call')
|
|
120
|
+
continue;
|
|
121
|
+
segment.calls.push(readCall(content, message.Name));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
// Reasoning blocks are re-sent as full snapshots on every chunk. The previous
|
|
125
|
+
// snapshot is only used to detect whether a chunk carries anything new; the
|
|
126
|
+
// callback always receives the whole text, because ACP renders thoughts with
|
|
127
|
+
// agent_thought (a complete replacement), never by appending chunks.
|
|
128
|
+
async function applyThought(event, data, state) {
|
|
129
|
+
const message = data.Message;
|
|
130
|
+
if (message?.Type !== 'thought')
|
|
131
|
+
return false;
|
|
132
|
+
// A finished block is dropped unless it already started here, so a replayed
|
|
133
|
+
// block cannot show up on its own.
|
|
134
|
+
const id = String(message.MessageId || `thought_${state.segment.thoughts.length}`);
|
|
135
|
+
const title = String(message.Title || '');
|
|
136
|
+
const text = (message.Contents ?? [])
|
|
137
|
+
.filter((content) => content.Type === 'text' && typeof content.Text === 'string')
|
|
138
|
+
.map((content) => String(content.Text))
|
|
139
|
+
.join('');
|
|
140
|
+
const seen = state.thoughtTail.get(id);
|
|
141
|
+
if (seen === undefined && event === 'message.done')
|
|
142
|
+
return true;
|
|
143
|
+
// Anything but an exact repeat of the previous snapshot is new content;
|
|
144
|
+
// a rewrite also counts, so the replacement is sent again.
|
|
145
|
+
const hasNewText = text !== seen;
|
|
146
|
+
state.thoughtTail.set(id, text);
|
|
147
|
+
if (!hasNewText)
|
|
148
|
+
return true;
|
|
149
|
+
return recordThought(state, { id, title, text });
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Read the context window usage off a completed response.
|
|
153
|
+
*
|
|
154
|
+
* Backends report `contextWindowTokensUsed`, usually with a matching
|
|
155
|
+
* `contextWindowLimit`. The limit is optional here because a backend may omit
|
|
156
|
+
* it; the caller can fall back to the model's contextLength.
|
|
157
|
+
*/
|
|
158
|
+
function readContextUsage(response) {
|
|
159
|
+
const extra = response?.ExtraInfo;
|
|
160
|
+
if (!extra)
|
|
161
|
+
return undefined;
|
|
162
|
+
const usedTokens = readCount(extra.contextWindowTokensUsed);
|
|
163
|
+
if (usedTokens === undefined)
|
|
164
|
+
return undefined;
|
|
165
|
+
const limitTokens = readCount(extra.contextWindowLimit);
|
|
166
|
+
return {
|
|
167
|
+
usedTokens,
|
|
168
|
+
...(limitTokens !== undefined && limitTokens > 0 ? { limitTokens } : {}),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function readCount(value) {
|
|
172
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
173
|
+
}
|
|
174
|
+
async function recordThought(state, thought) {
|
|
175
|
+
const existing = state.segment.thoughts.find((item) => item.id === thought.id);
|
|
176
|
+
if (existing)
|
|
177
|
+
existing.text = thought.text;
|
|
178
|
+
else
|
|
179
|
+
state.segment.thoughts.push(thought);
|
|
180
|
+
await state.callbacks.onThought?.(thought);
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
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
|
+
function readCall(content, fallbackName) {
|
|
211
|
+
const raw = content.Arguments;
|
|
212
|
+
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
213
|
+
return {
|
|
214
|
+
callId: String(content.CallId ?? ''),
|
|
215
|
+
name: String(content.Name || fallbackName || ''),
|
|
216
|
+
arguments: parsed && typeof parsed === 'object' ? parsed : {},
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
//# sourceMappingURL=sse.js.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
export function sseLogFile() {
|
|
5
|
+
return process.env.PORTAL_SSE_LOG ?? path.join(homedir(), '.portal', 'logs', 'sse.log');
|
|
6
|
+
}
|
|
7
|
+
// Already-buffered bodies only. A live response is logged by loggedSseBody,
|
|
8
|
+
// on the same read as the parser, so logging never owns a second stream.
|
|
9
|
+
export function logSse(label, body) {
|
|
10
|
+
remember(sseLogFile(), `\n----- ${new Date().toISOString()} ${label}\n${body}`);
|
|
11
|
+
}
|
|
12
|
+
// One reader. Chunks are forwarded to the caller and, separately, appended to
|
|
13
|
+
// the log. A failed or partial log write is discarded: it must not reject the
|
|
14
|
+
// chat, and it must not leave a promise that can crash the process.
|
|
15
|
+
export function loggedSseBody(label, body) {
|
|
16
|
+
const file = sseLogFile();
|
|
17
|
+
remember(file, `\n----- ${new Date().toISOString()} ${label}\n`);
|
|
18
|
+
const reader = body.getReader();
|
|
19
|
+
const decoder = new TextDecoder();
|
|
20
|
+
return new ReadableStream({
|
|
21
|
+
async pull(controller) {
|
|
22
|
+
const { done, value } = await reader.read();
|
|
23
|
+
if (done) {
|
|
24
|
+
remember(file, decoder.decode());
|
|
25
|
+
controller.close();
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
remember(file, decoder.decode(value, { stream: true }));
|
|
29
|
+
controller.enqueue(value);
|
|
30
|
+
},
|
|
31
|
+
cancel(reason) {
|
|
32
|
+
return reader.cancel(reason).catch(() => undefined);
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function remember(file, text) {
|
|
37
|
+
if (!text)
|
|
38
|
+
return;
|
|
39
|
+
try {
|
|
40
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
41
|
+
appendFileSync(file, text);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// Logging is optional. A failed or partial write must not reject the chat.
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=sseLog.js.map
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { PortalClient } from './client.js';
|
|
2
|
+
export interface RuntimeModel {
|
|
3
|
+
id: string;
|
|
4
|
+
label?: string;
|
|
5
|
+
modelId?: string;
|
|
6
|
+
name?: string;
|
|
7
|
+
modelName?: string;
|
|
8
|
+
contextLength?: number | null;
|
|
9
|
+
supportsReasoning?: boolean;
|
|
10
|
+
supportedReasoningEfforts?: string[];
|
|
11
|
+
canDisableReasoning?: boolean;
|
|
12
|
+
defaultReasoningEffort?: string;
|
|
13
|
+
}
|
|
14
|
+
export declare const ALL_REASONING_EFFORTS: string[];
|
|
15
|
+
export interface WorkbenchTarget {
|
|
16
|
+
agentId: string;
|
|
17
|
+
models: RuntimeModel[];
|
|
18
|
+
defaultModelId: string;
|
|
19
|
+
defaultReasoningEffort: string;
|
|
20
|
+
}
|
|
21
|
+
export declare function loadWorkbench(client: PortalClient, spaceId: string): Promise<WorkbenchTarget>;
|
|
22
|
+
export declare function resolveTarget(client: PortalClient, spaceId: string): Promise<{
|
|
23
|
+
agentId: string;
|
|
24
|
+
modelId: string;
|
|
25
|
+
reasoningEffort: string;
|
|
26
|
+
}>;
|
|
27
|
+
/**
|
|
28
|
+
* Reasoning levels the given model actually accepts.
|
|
29
|
+
*
|
|
30
|
+
* The server resolves provider-native levels into these Portal levels, so the
|
|
31
|
+
* client must not invent its own list: a model that only supports low/medium/high
|
|
32
|
+
* would otherwise show minimal and xhigh and fail on selection. An older server
|
|
33
|
+
* omits the capabilities, in which case every level is offered as before.
|
|
34
|
+
*/
|
|
35
|
+
export declare function reasoningEfforts(model: RuntimeModel | undefined): string[];
|
|
36
|
+
export declare function isReasoningEffort(model: RuntimeModel | undefined, value: string): boolean;
|
|
37
|
+
/** Session default: the server-configured level when that model still supports it. */
|
|
38
|
+
export declare function defaultReasoningEffort(model: RuntimeModel | undefined, configured?: string): string;
|
|
39
|
+
export declare function pickModel(models: RuntimeModel[], defaultModelId: string, requested?: string): RuntimeModel | undefined;
|
|
40
|
+
//# sourceMappingURL=target.d.ts.map
|