@kingsoftcloud/agentkit-harness-ui 0.0.18 → 0.0.20
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/package.json +2 -2
- package/src/components.mjs +1 -1
- package/src/engine-view/adapter.mjs +87 -12
- package/src/engine-view/app.mjs +2 -2
- package/src/host/session-task-events.mjs +65 -9
- package/src/host/state/native-runtime-route.mjs +3 -2
- package/src/host/state/native-status-panel.mjs +6 -0
- package/src/host/task-timeline.mjs +26 -13
- package/src/index.mjs +1 -1
- package/src/project.mjs +2 -2
- package/src/protocol.mjs +7 -1
- package/src/react-binding.mjs +121 -1
- package/src/reducer.mjs +39 -1
- package/src/renderers.mjs +89 -49
- package/src/styles.mjs +46 -5
- package/src/tool-error.mjs +32 -4
- package/src/view.mjs +28 -6
- package/src/work-segments.mjs +2 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kingsoftcloud/agentkit-harness-ui",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.20",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Reusable React task-process UI for AgentKit Native: an explicitly versioned event protocol, a pure state reducer, and an accessible timeline. No Studio/DSH/Python imports; React is a peer dependency.",
|
|
@@ -98,6 +98,6 @@
|
|
|
98
98
|
"registry": "https://registry.npmjs.org"
|
|
99
99
|
},
|
|
100
100
|
"dependencies": {
|
|
101
|
-
"@kingsoftcloud/agentkit-harness-core": "0.0.
|
|
101
|
+
"@kingsoftcloud/agentkit-harness-core": "0.0.20"
|
|
102
102
|
}
|
|
103
103
|
}
|
package/src/components.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as React from "react";
|
|
2
2
|
import { createHarnessComponents } from "./react-binding.mjs";
|
|
3
|
-
export const { HarnessTimeline } = createHarnessComponents(React);
|
|
3
|
+
export const { HarnessTimeline, HarnessTurn } = createHarnessComponents(React);
|
|
4
4
|
export { buildViewModel, styles } from "./react-binding.mjs";
|
|
5
5
|
|
|
6
6
|
import * as ReactDOM from "react-dom";
|
|
@@ -4,30 +4,65 @@
|
|
|
4
4
|
// adapter turns them into the timeline's own event stream. It is deterministic
|
|
5
5
|
// and keyed by engine sequence numbers, so replaying any prefix is a no-op.
|
|
6
6
|
import { PROTOCOL_VERSION } from "../protocol.mjs";
|
|
7
|
+
import { toolIdentity } from "../tool-identity.mjs";
|
|
7
8
|
|
|
8
9
|
export const ENGINE_EVENT_SCHEMA = "agentkit.engine-event/v1";
|
|
9
10
|
export const ENGINE_VIEW_CONTRACT = "agentkit.engine-view/v1";
|
|
11
|
+
export const FINAL_SUBMISSION_TOOL = "submit_final_output";
|
|
10
12
|
|
|
11
13
|
const OUTCOMES = new Set(["completed", "unverified", "blocked", "failed", "cancelled"]);
|
|
12
14
|
const text = value => typeof value === "string" && value.trim().length > 0;
|
|
13
15
|
const input = value => value === undefined || value === null ? {} : typeof value === "object" ? value : { value };
|
|
14
16
|
|
|
17
|
+
function completedEditDisplay(event) {
|
|
18
|
+
const kind = toolIdentity(event.title)?.family;
|
|
19
|
+
const { ok, path, diff_additions: added, diff_deletions: removed } = event.result ?? {};
|
|
20
|
+
if (!["edit", "write"].includes(kind) || ok !== true || !text(path)
|
|
21
|
+
|| ![added, removed].every(count => Number.isSafeInteger(count) && count >= 0)) return undefined;
|
|
22
|
+
return { kind: "file_edit", files: [{ path, changeStat: { added, removed }, operationKind: kind === "write" ? "write" : "edit" }] };
|
|
23
|
+
}
|
|
24
|
+
|
|
15
25
|
function outcomeOf(event) {
|
|
16
26
|
if (event.title === "failed" || event.status === "failed") return "failed";
|
|
17
|
-
if (event.title
|
|
27
|
+
if (["canceled", "cancelled"].includes(event.title) || ["canceled", "cancelled"].includes(event.status)) return "cancelled";
|
|
28
|
+
if (event.status === "verified") return "completed";
|
|
18
29
|
if (OUTCOMES.has(event.status)) return event.status;
|
|
19
30
|
return event.title === "completed" ? "completed" : "unverified";
|
|
20
31
|
}
|
|
21
32
|
|
|
33
|
+
function toolFailure(result, name) {
|
|
34
|
+
const code = result?.error_type ?? result?.code ?? result?.error_code;
|
|
35
|
+
const message = result?.error_message ?? result?.message;
|
|
36
|
+
if (!text(code)) return { message: text(message) ? message : `工具 ${name ?? ""} 未成功`.trim() };
|
|
37
|
+
const reason = code === 'command_policy_blocked' && result?.executed === false ? result.finding?.detail : undefined;
|
|
38
|
+
return { code, ...(text(reason) ? { message: reason } : text(message) ? { message } : {}),
|
|
39
|
+
...(Number.isSafeInteger(result.failed_edit_index) && result.failed_edit_index >= 0
|
|
40
|
+
? { failed_edit_index: result.failed_edit_index } : {}) };
|
|
41
|
+
}
|
|
42
|
+
|
|
22
43
|
/** Convert one engine event; returns zero or more harness-ui events. */
|
|
23
|
-
export function engineEventToTimeline(event, { runId = "run" } = {}) {
|
|
44
|
+
export function engineEventToTimeline(event, { runId = "run", time, startedAt = time } = {}) {
|
|
24
45
|
if (!event || event.schema !== ENGINE_EVENT_SCHEMA || !Number.isSafeInteger(event.seq)) return [];
|
|
25
46
|
const v = PROTOCOL_VERSION, id = suffix => `${runId}:${event.seq}:${suffix}`;
|
|
47
|
+
const thoughtId = typeof event.requestId === "string" && /^[a-f0-9]{64}$/.test(event.requestId)
|
|
48
|
+
? `${runId}:thought:${event.requestId}` : id("thought");
|
|
26
49
|
switch (event.kind) {
|
|
27
50
|
case "run.started":
|
|
28
|
-
return [{ v, id: id("start"), type: "task.started", taskId: runId, runId }];
|
|
51
|
+
return [{ v, id: id("start"), type: "task.started", taskId: runId, runId, startedAt }];
|
|
52
|
+
case "todo.initialized":
|
|
53
|
+
case "todo.updated":
|
|
54
|
+
return Object.hasOwn(event, "plan") ? [{ v, id: id("todo"), type: "plan.updated",
|
|
55
|
+
items: event.plan?.items ?? [], completedCount: event.plan?.completedCount, totalCount: event.plan?.totalCount }] : [];
|
|
56
|
+
case "effect.prepared":
|
|
57
|
+
case "effect.settled":
|
|
58
|
+
return event.category === "model" && event.title === "request"
|
|
59
|
+
? [{ v, id: id("model-request"), type: "model.request", active: event.kind === "effect.prepared",
|
|
60
|
+
retry: event.kind === "effect.prepared" && event.retry === true,
|
|
61
|
+
...(event.purpose === "compaction" ? { purpose: "compaction" } : {}), itemId: thoughtId }]
|
|
62
|
+
: [];
|
|
29
63
|
case "model.completed": {
|
|
30
64
|
const out = [];
|
|
65
|
+
if (text(event.thinking)) out.push({ v, id: id("thought-done"), type: "thinking.done", itemId: thoughtId, text: event.thinking });
|
|
31
66
|
// Commentary that accompanies tool calls is progress, not the answer.
|
|
32
67
|
if (text(event.detail) && (event.title === "initial_plan" || Array.isArray(event.calls) && event.calls.length)) {
|
|
33
68
|
const itemId = `${runId}:note:${event.seq}`;
|
|
@@ -35,29 +70,43 @@ export function engineEventToTimeline(event, { runId = "run" } = {}) {
|
|
|
35
70
|
{ v, id: id("note-done"), type: "text.done", itemId });
|
|
36
71
|
}
|
|
37
72
|
for (const call of Array.isArray(event.calls) ? event.calls : []) {
|
|
38
|
-
if (!text(call?.callId) || !text(call?.name)) continue;
|
|
73
|
+
if (!text(call?.callId) || !text(call?.name) || call.name === FINAL_SUBMISSION_TOOL) continue;
|
|
39
74
|
out.push({ v, id: id(`call:${call.callId}`), type: "tool.scheduled", callId: call.callId, name: call.name, input: input(call.arguments) },
|
|
40
75
|
{ v, id: id(`run:${call.callId}`), type: "tool.started", callId: call.callId });
|
|
41
76
|
}
|
|
42
77
|
return out;
|
|
43
78
|
}
|
|
79
|
+
case "model.stream_interrupted":
|
|
80
|
+
return text(event.thinking)
|
|
81
|
+
? [{ v, id: id("thought-done"), type: "thinking.done", itemId: thoughtId, text: event.thinking }]
|
|
82
|
+
: [];
|
|
44
83
|
case "tool.completed": {
|
|
45
84
|
if (!text(event.callId)) return [];
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
85
|
+
// Older engines stored the committed TodoWrite receipt but omitted the
|
|
86
|
+
// separate checklist projection. Never infer progress from tool inputs.
|
|
87
|
+
const display = event.status === "ok" ? completedEditDisplay(event) : undefined;
|
|
88
|
+
if (event.status !== "ok") return [{ v, id: id("error"), type: "tool.error", callId: event.callId,
|
|
89
|
+
error: toolFailure(event.result, event.title) }];
|
|
90
|
+
const out = [{ v, id: id("result"), type: "tool.result", callId: event.callId, result: event.result ?? null,
|
|
91
|
+
...(display ? { display } : {}) }];
|
|
92
|
+
if (event.title === "TodoWrite" && Array.isArray(event.result?.todos))
|
|
93
|
+
out.push({ v, id: id("todo-receipt"), type: "plan.updated",
|
|
94
|
+
items: event.result.todos.map((item, index) => ({ ...item, id: `todo:${index}` })) });
|
|
95
|
+
return out;
|
|
50
96
|
}
|
|
51
|
-
case "model.
|
|
52
|
-
return [{ v, id: id("
|
|
97
|
+
case "model.retry_exhausted":
|
|
98
|
+
return [{ v, id: id("paused"), type: "task.state", state: "paused", reason: "provider_unavailable",
|
|
99
|
+
message: event.modelError }];
|
|
53
100
|
case "run.terminal": {
|
|
54
101
|
const out = [];
|
|
102
|
+
const itemId = `${runId}:final`;
|
|
55
103
|
if (text(event.detail)) {
|
|
56
|
-
const itemId = `${runId}:final`;
|
|
57
104
|
out.push({ v, id: id("final"), type: "text.delta", itemId, delta: event.detail }, { v, id: id("final-done"), type: "text.done", itemId });
|
|
58
105
|
}
|
|
59
106
|
if (event.title === "paused") return [...out, { v, id: id("paused"), type: "task.state", state: "paused", reason: event.reason ?? null }];
|
|
60
|
-
return [...out, { v, id: id("finished"), type: "task.finished", outcome: outcomeOf(event),
|
|
107
|
+
return [...out, { v, id: id("finished"), type: "task.finished", outcome: outcomeOf(event), endedAt: time,
|
|
108
|
+
...(out.length ? { finalAnswerId: itemId } : {}), ...(event.reason ? { reason: event.reason } : {}),
|
|
109
|
+
...(text(event.modelError) ? { error: event.modelError } : {}) }];
|
|
61
110
|
}
|
|
62
111
|
default:
|
|
63
112
|
return [];
|
|
@@ -67,3 +116,29 @@ export function engineEventToTimeline(event, { runId = "run" } = {}) {
|
|
|
67
116
|
export function engineEventsToTimeline(events, options) {
|
|
68
117
|
return (Array.isArray(events) ? events : []).flatMap(event => engineEventToTimeline(event, options));
|
|
69
118
|
}
|
|
119
|
+
|
|
120
|
+
export function relativeDeliveryPath(path) {
|
|
121
|
+
return typeof path === "string" && path.length <= 2048 && !/[\\:\u0000-\u001f\u007f?#]/u.test(path)
|
|
122
|
+
&& path.split("/").every(part => part && part !== "." && part !== "..");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Web cards come from the Run's manifest. Older Runs can name an HTML file
|
|
126
|
+
* explicitly in the final answer; the host still has to confirm it exists. */
|
|
127
|
+
export function engineWebDeliveries(event) {
|
|
128
|
+
if (event?.schema !== ENGINE_EVENT_SCHEMA || event.kind !== "run.terminal" || event.title !== "completed"
|
|
129
|
+
|| !text(event.detail)) return [];
|
|
130
|
+
const declared = Array.isArray(event.deliverables) ? event.deliverables : [];
|
|
131
|
+
const web = declared.find(item => item?.kind === "web" && relativeDeliveryPath(item.path)
|
|
132
|
+
&& /\.html?$/i.test(item.path) && (item.root === "." || relativeDeliveryPath(item.root)
|
|
133
|
+
&& item.path.startsWith(item.root + "/")));
|
|
134
|
+
if (web) return [{ path: web.path, root: web.root }];
|
|
135
|
+
if (declared.length) return [];
|
|
136
|
+
|
|
137
|
+
const paths = new Set();
|
|
138
|
+
for (const match of event.detail.matchAll(/`([^`\r\n]+)`|\]\(([^\s()]+)\)/g)) {
|
|
139
|
+
const path = (match[1] ?? match[2]).replace(/^\.\//, "");
|
|
140
|
+
if (relativeDeliveryPath(path) && !/[%<>]/.test(path) && /\.html?$/i.test(path)) paths.add(path);
|
|
141
|
+
if (paths.size >= 8) break;
|
|
142
|
+
}
|
|
143
|
+
return [...paths].map(path => ({ path }));
|
|
144
|
+
}
|
package/src/engine-view/app.mjs
CHANGED
|
@@ -18,7 +18,7 @@ import { initialState, reduceAll } from "../reducer.mjs";
|
|
|
18
18
|
import { engineEventsToTimeline, ENGINE_VIEW_CONTRACT } from "./adapter.mjs";
|
|
19
19
|
|
|
20
20
|
const VERSION = globalThis.__ENGINE_VIEW_VERSION__ ?? "dev";
|
|
21
|
-
const {
|
|
21
|
+
const { HarnessTurn } = createHarnessComponents(React);
|
|
22
22
|
const post = message => { try { window.parent.postMessage({ contract: ENGINE_VIEW_CONTRACT, ...message }, "*"); } catch { /* detached */ } };
|
|
23
23
|
|
|
24
24
|
function App() {
|
|
@@ -48,7 +48,7 @@ function App() {
|
|
|
48
48
|
observer.observe(root);
|
|
49
49
|
return () => { window.removeEventListener("message", onMessage); observer.disconnect(); };
|
|
50
50
|
}, []);
|
|
51
|
-
return React.createElement(
|
|
51
|
+
return React.createElement(HarnessTurn, { state: view.state, theme: view.theme, autoFollow: false, styleSheet: null });
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
createRoot(document.getElementById("root")).render(React.createElement(App));
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { initialState, reduce } from '@kingsoftcloud/agentkit-harness-ui/reducer';
|
|
2
2
|
import { previewToolInput } from '@kingsoftcloud/agentkit-harness-ui/input-preview';
|
|
3
3
|
import { nativeRunIsInactive } from './state/native-outcome.mjs';
|
|
4
|
+
import { ENGINE_EVENT_SCHEMA, FINAL_SUBMISSION_TOOL, engineEventToTimeline, engineWebDeliveries } from '../engine-view/adapter.mjs';
|
|
4
5
|
|
|
5
6
|
const textOf = content => (Array.isArray(content) ? content : []).filter(part => part.type === 'text').map(part => part.text).join('\n');
|
|
6
7
|
const nativeInterruptionMessages = Object.freeze({
|
|
@@ -55,7 +56,8 @@ function admittedContextMarker(event, sessionId) {
|
|
|
55
56
|
}
|
|
56
57
|
|
|
57
58
|
export function createSessionTaskProjector({ sessionId } = {}) {
|
|
58
|
-
let revision = -1, previousWindow = null, tasks = new Map(), result = [], activeTurn = null, settledSteps = new Set(), previews = new Map(), finalAnswers = new Map(), dispositions = new Map();
|
|
59
|
+
let revision = -1, previousWindow = null, tasks = new Map(), result = [], activeTurn = null, settledSteps = new Set(), previews = new Map(), finalAnswers = new Map(), dispositions = new Map(), engineTurns = new Map(), replies = new Map();
|
|
60
|
+
let settledEngineThoughts = new Set();
|
|
59
61
|
const apply = entry => {
|
|
60
62
|
const event = entry.event, data = event?.data;
|
|
61
63
|
if (!event || !data) return;
|
|
@@ -84,6 +86,7 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
84
86
|
if (!task) task = reduce(initialState(), { v: 1, type: 'task.started', id: `turn:${turn}`, taskId: String(turn),
|
|
85
87
|
...(event.type === 'turn/start' ? { startedAt: event.time } : {}) });
|
|
86
88
|
const prefix = `${turn}:${data.step ?? 0}`, source = `${entry.type}:${event.seq}`;
|
|
89
|
+
const engineBlock = index => `${turn}:engine-thought:${index}`;
|
|
87
90
|
const responseId = typeof sessionId === 'string' && sessionId && Number.isSafeInteger(data.step) && data.step > 0
|
|
88
91
|
? JSON.stringify([sessionId, turn, data.step]) : null;
|
|
89
92
|
// The host retains successful attempt frames until step/end so its own
|
|
@@ -94,6 +97,22 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
94
97
|
let index = 0;
|
|
95
98
|
const emit = (type, value) => { task = reduce(task, { v: 1, type, id: `${source}:${index++}`, ts: event.time, ...value }); };
|
|
96
99
|
if (event.type === 'turn/start' && task.taskStartedAt === null) emit('task.started', { taskId: String(turn), startedAt: event.time });
|
|
100
|
+
if (event.type === 'agentkit/native-engine-event' && event.ignorable === true
|
|
101
|
+
&& typeof data.runId === 'string' && data.runId && data.event?.schema === ENGINE_EVENT_SCHEMA
|
|
102
|
+
&& Number.isSafeInteger(data.event.seq)) {
|
|
103
|
+
const previous = engineTurns.get(turn);
|
|
104
|
+
if (previous && (previous.runId !== data.runId || previous.seq >= data.event.seq)) return;
|
|
105
|
+
const terminal = data.event.kind === 'run.terminal';
|
|
106
|
+
engineTurns.set(turn, { runId: data.runId, seq: data.event.seq, terminal,
|
|
107
|
+
...(terminal ? { deliveries: engineWebDeliveries(data.event).map(item => ({ ...item, seq: event.seq })),
|
|
108
|
+
...(data.event.title === 'completed' ? { deliverySeq: event.seq } : {}) } : {}) });
|
|
109
|
+
if (Number.isSafeInteger(data.settledThinkingBlock) && data.settledThinkingBlock >= 0)
|
|
110
|
+
settledEngineThoughts.add(engineBlock(data.settledThinkingBlock));
|
|
111
|
+
for (const frame of engineEventToTimeline(data.event, { runId: data.runId, time: event.time, startedAt: task.taskStartedAt ?? event.time }))
|
|
112
|
+
task = reduce(task, frame);
|
|
113
|
+
tasks.set(turn, task);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
97
116
|
const block = (value, position, done = true, sourceMessageId) => {
|
|
98
117
|
const itemId = `${prefix}:block:${position}`;
|
|
99
118
|
if (value.type === 'text') emit(done ? 'text.done' : 'text.delta', { itemId, ...(responseId ? { responseId } : {}), ...(sourceMessageId ? { sourceMessageId } : {}), ...(done ? { text: value.text } : { delta: value.text }) });
|
|
@@ -101,11 +120,37 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
101
120
|
};
|
|
102
121
|
if (event.type === 'user/message' && ['user', 'user-rpc'].includes(data.source?.kind))
|
|
103
122
|
emit('text.done', { itemId: `user:${data.id ?? event.seq}`, text: textOf(data.content), role: 'user' });
|
|
123
|
+
const engine = engineTurns.get(turn);
|
|
124
|
+
if (event.type === 'agentkit/native-engine-tool-draft') {
|
|
125
|
+
if (event.ignorable !== true || engine?.runId !== data.runId || !task.modelThinkingId
|
|
126
|
+
|| !/^[a-f0-9]{64}$/.test(data.requestId) || task.modelThinkingId !== `${data.runId}:thought:${data.requestId}`
|
|
127
|
+
|| !Array.isArray(data.tools) || data.tools.length > 16) return;
|
|
128
|
+
for (const tool of data.tools) {
|
|
129
|
+
if (!Number.isSafeInteger(tool?.index) || tool.index < 0 || typeof tool.name !== 'string'
|
|
130
|
+
|| !/^[A-Za-z][A-Za-z0-9_.:/-]{0,127}$/.test(tool.name) || tool.name === FINAL_SUBMISSION_TOOL) continue;
|
|
131
|
+
emit('tool.preview', { previewId: `${task.modelThinkingId}:draft:${tool.index}`, name: tool.name, responseId: task.modelThinkingId });
|
|
132
|
+
}
|
|
133
|
+
tasks.set(turn, task);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (event.type === 'assistant/live-chunk' && engine) {
|
|
137
|
+
const chunk = data.chunk;
|
|
138
|
+
if (task.modelThinkingId && chunk?.type === 'reasoning-delta' && Number.isSafeInteger(chunk.index)
|
|
139
|
+
&& !settledEngineThoughts.has(engineBlock(chunk.index))
|
|
140
|
+
&& !task.items.some(item => item.kind === 'tool-preview' && item.responseId === task.modelThinkingId)) {
|
|
141
|
+
emit('thinking.delta', { itemId: task.modelThinkingId, responseId: task.modelThinkingId, delta: chunk.text });
|
|
142
|
+
tasks.set(turn, task);
|
|
143
|
+
}
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
104
146
|
if (event.type === 'assistant/message') {
|
|
105
147
|
const content = data.message?.content ?? [];
|
|
106
148
|
const textIndex = content.findLastIndex(part => part.type === 'text' && part.text?.trim());
|
|
107
|
-
|
|
108
|
-
|
|
149
|
+
const final = data.interrupted !== true && textIndex >= 0 && !content.some(part => part.type === 'tool-call');
|
|
150
|
+
finalAnswers.set(turn, final ? `${prefix}:block:${textIndex}` : null);
|
|
151
|
+
if (final) replies.set(turn, { messageId: data.message.id });
|
|
152
|
+
else replies.delete(turn);
|
|
153
|
+
if (engine && (task.finalAnswerId || !final)) return;
|
|
109
154
|
content.forEach((part, i) => {
|
|
110
155
|
block(part, i, true, data.message.id);
|
|
111
156
|
// A host may publish the live dispatch before the committed assistant
|
|
@@ -117,7 +162,7 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
117
162
|
}
|
|
118
163
|
});
|
|
119
164
|
}
|
|
120
|
-
if (event.type === 'assistant/live-chunk') {
|
|
165
|
+
if (event.type === 'assistant/live-chunk' && !engine) {
|
|
121
166
|
const chunk = data.chunk;
|
|
122
167
|
if (chunk?.type === 'text-delta') block({ type: 'text', text: chunk.text }, chunk.index, false);
|
|
123
168
|
if (chunk?.type === 'reasoning-delta') block({ type: 'reasoning', text: chunk.text }, chunk.index, false);
|
|
@@ -133,24 +178,30 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
133
178
|
...(responseId ? { responseId } : {}) });
|
|
134
179
|
}
|
|
135
180
|
}
|
|
136
|
-
if (event.type === 'tool/call') {
|
|
181
|
+
if (event.type === 'tool/call' && !engine) {
|
|
137
182
|
let input = {}; try { input = typeof data.arguments === 'string' ? JSON.parse(data.arguments) : data.arguments; } catch { /* incomplete arguments */ }
|
|
138
183
|
emit('tool.scheduled', { callId: data.callId, name: data.name, input, ...(responseId ? { responseId } : {}) });
|
|
139
184
|
}
|
|
140
|
-
if (event.type === 'tool/result') {
|
|
185
|
+
if (event.type === 'tool/result' && !engine) {
|
|
141
186
|
const message = data.message;
|
|
142
187
|
const text = textOf(message?.content); let value;
|
|
143
188
|
try { value = JSON.parse(text); } catch { /* plain tool result */ }
|
|
189
|
+
const name = task.items.find(item => item.callId === message?.toolCallId)?.name;
|
|
144
190
|
const display = data.meta?.contract === 'agentkit.workspace-display/v1' ? data.meta.display
|
|
145
|
-
: commandDisplay(
|
|
191
|
+
: commandDisplay(name, value);
|
|
192
|
+
const workspaceObservation = (name === 'read_workspace_file' || name === 'search_workspace_files') && value?.ok === true;
|
|
146
193
|
if (dispositions.has(`${turn}:${message?.toolCallId}`)) emit('tool.state', { callId: message.toolCallId, status: 'not_dispatched' });
|
|
147
194
|
else if (uncertainFact(data.meta?.nativeOutcome, message?.toolCallId, turn, sessionId) || value?.status === 'uncertain') emit('tool.state', { callId: message?.toolCallId, status: 'uncertain', message: '执行结果未知,需要核对回执' });
|
|
148
195
|
else emit(message?.isError ? 'tool.error' : 'tool.result', { callId: message?.toolCallId,
|
|
149
|
-
...(message?.isError ? { error: text } : { result: text,
|
|
196
|
+
...(message?.isError ? { error: text } : { result: workspaceObservation ? value : text,
|
|
150
197
|
...(display ? { display } : {}) }) });
|
|
151
198
|
}
|
|
152
199
|
if (event.type === 'turn/end') {
|
|
153
200
|
const reason = data.reason;
|
|
201
|
+
if (replies.has(turn)) replies.set(turn, { ...replies.get(turn), time: event.time, seq: event.seq,
|
|
202
|
+
branchable: reason?.kind === 'completed' });
|
|
203
|
+
if (engine?.terminal && (task.finalAnswerId || !finalAnswers.get(turn) || reason?.kind !== 'completed')) return;
|
|
204
|
+
if (engine && task.taskState === 'paused' && task.taskReason === 'provider_unavailable' && reason?.kind === 'error') return;
|
|
154
205
|
const interruption = reason?.kind === 'error' && typeof reason.error?.code === 'string'
|
|
155
206
|
&& Object.hasOwn(nativeInterruptionMessages, reason.error.code) ? nativeInterruptionMessages[reason.error.code] : null;
|
|
156
207
|
const outcome = interruption ? 'unverified' : reason?.kind === 'completed' ? 'unverified' : reason?.kind === 'blocked' ? 'blocked'
|
|
@@ -179,12 +230,17 @@ export function createSessionTaskProjector({ sessionId } = {}) {
|
|
|
179
230
|
const append = suffix !== null && !suffix.some(entry => entry.event?.type === 'assistant/message');
|
|
180
231
|
if (!append) {
|
|
181
232
|
tasks = new Map(); activeTurn = null; previews = new Map(); finalAnswers = new Map(); dispositions = new Map();
|
|
233
|
+
engineTurns = new Map(); replies = new Map(); settledEngineThoughts = new Set();
|
|
182
234
|
settledSteps = new Set((window.entries ?? []).filter(entry => entry.event?.type === 'assistant/message')
|
|
183
235
|
.map(entry => `${entry.event.data.turn}:${entry.event.data.step ?? 0}`));
|
|
184
236
|
}
|
|
185
237
|
for (const entry of append ? suffix : window.entries ?? []) apply(entry);
|
|
186
238
|
revision = window.revision;previousWindow = window;
|
|
187
|
-
result = [...tasks].sort(([a], [b]) => a - b).map(([turn, state]) => ({
|
|
239
|
+
result = [...tasks].sort(([a], [b]) => a - b).map(([turn, state]) => ({
|
|
240
|
+
turn, state, ...(replies.has(turn) ? { reply: replies.get(turn) } : {}),
|
|
241
|
+
...(state.finalAnswerId && engineTurns.get(turn)?.deliverySeq !== undefined
|
|
242
|
+
? { deliveries: engineTurns.get(turn).deliveries, deliverySeq: engineTurns.get(turn).deliverySeq } : {}),
|
|
243
|
+
}));
|
|
188
244
|
return result;
|
|
189
245
|
},
|
|
190
246
|
};
|
|
@@ -7,7 +7,7 @@ export function nativeRuntimeRouteInput(_session, openState, projection, boundPr
|
|
|
7
7
|
return { presetId: boundPresetId, ready: openState === 'open' && projection?.state === 'ready' };
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
export async function resolveNativeRuntimeRoute({ hostRemote, presetId, resolveAgentFromPreset, signal }) {
|
|
10
|
+
export async function resolveNativeRuntimeRoute({ hostRemote, presetId, resolveAgentFromPreset, isIndependentPreset, signal }) {
|
|
11
11
|
const first = await hostRemote.agents({ source: 'local', pageSize: 100 });
|
|
12
12
|
signal.throwIfAborted();
|
|
13
13
|
if (!Array.isArray(first?.items)) throw Error('智能体目录响应无效');
|
|
@@ -22,5 +22,6 @@ export async function resolveNativeRuntimeRoute({ hostRemote, presetId, resolveA
|
|
|
22
22
|
if (!agentId) return { kind: 'other', agentId: null };
|
|
23
23
|
const agent = items.find(item => (item.metadata?.id ?? item.id) === agentId);
|
|
24
24
|
if (!agent) throw Error('当前会话的智能体配置暂不可用');
|
|
25
|
-
|
|
25
|
+
if (agent.spec?.runtime?.type !== 'harness') return { kind: 'other', agentId };
|
|
26
|
+
return { kind: isIndependentPreset?.(presetId) ? 'engine' : 'native', agentId };
|
|
26
27
|
}
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
export function engineStatusPanelModel(tasks, running) {
|
|
2
|
+
const latest = tasks.findLast(task => task.state.planSummary);
|
|
3
|
+
const plan = latest?.state.plan ? { items: latest.state.plan, ...latest.state.planSummary } : null;
|
|
4
|
+
return { git: null, plan, terminals: [], agents: [], isRunning: Boolean(running) };
|
|
5
|
+
}
|
|
6
|
+
|
|
1
7
|
/** Host facts adapted to the independent status presentation. No execution capability. */
|
|
2
8
|
export function nativeStatusPanelModel(status, children = [], commandObservations = []) {
|
|
3
9
|
const activity = status?.activity;
|
|
@@ -3,7 +3,7 @@ import { installNativeCommandPane } from './native-command-pane.mjs';
|
|
|
3
3
|
import { createHarnessComponents } from '@kingsoftcloud/agentkit-harness-ui/react-binding';
|
|
4
4
|
import { createMarkdownComponents, markdownStyles } from '@kingsoftcloud/agentkit-harness-ui/markdown';
|
|
5
5
|
import { createStatusPanelComponents, statusPanelStyles } from '@kingsoftcloud/agentkit-harness-ui/status-panel';
|
|
6
|
-
import { nativeStatusPanelModel } from './state/native-status-panel.mjs';
|
|
6
|
+
import { engineStatusPanelModel, nativeStatusPanelModel } from './state/native-status-panel.mjs';
|
|
7
7
|
import { nativeTaskWorkspaceRoot, taskWorkspaceFileTarget } from './state/task-links.mjs';
|
|
8
8
|
import { resolveNativeRuntimeRoute, nativeRuntimeRouteInput } from './state/native-runtime-route.mjs';
|
|
9
9
|
import { createNativeTaskReadModel } from './state/native-task-read-model.mjs';
|
|
@@ -16,7 +16,9 @@ const labels = { result: '执行结果', thought: '思考', running: '执行中'
|
|
|
16
16
|
waiting: '等待确认或回执', paused: '已暂停', toolScheduled: '排队中', toolRunning: '执行中', toolCompleted: '已返回',
|
|
17
17
|
toolFailed: '执行失败', toolUncertain: '执行结果未知', toolNotDispatched: '未执行', jumpLatest: '回到最新',
|
|
18
18
|
readKind: '读取', readReading: '读取中', listKind: '列出文件', listSearching: '列出文件中', searchKind: '搜索', searchSearching: '搜索中',
|
|
19
|
-
|
|
19
|
+
searchQuery: '搜索词', searchScope: '搜索范围', searchGlob: '文件匹配规则', searchMatches: '返回命中数', searchResultsTruncated: '部分命中位置已省略',
|
|
20
|
+
readPath: '文件路径', readLines: '已读取行', readRequestedLines: '请求读取行', readOffset: '起始偏移', readLimit: '读取上限',
|
|
21
|
+
readFromLine: '从第 {line} 行开始', readThroughLine: '截至第 {line} 行', readNoLines: '未返回文本行',
|
|
20
22
|
copy: '复制', openFile: '打开文件', openTerminal: '查看终端输出', noOutput: '没有输出', inspect: '查看详情',
|
|
21
23
|
expandCommand: '展开命令', collapseCommand: '收起命令',
|
|
22
24
|
toolDetails: '工具详情', close: '关闭', state: '状态', arguments: '调用参数', noSettledResult: '尚无已确认的结果', appliedChanges: '实际文件变更',
|
|
@@ -27,11 +29,11 @@ const labels = { result: '执行结果', thought: '思考', running: '执行中'
|
|
|
27
29
|
toolPreparing: '正在生成工具参数', previewStopped: '工具参数生成已中断' };
|
|
28
30
|
|
|
29
31
|
/** Only the transport adapter and runtime controls belong to Studio. */
|
|
30
|
-
export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPreset }) {
|
|
32
|
+
export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPreset, isIndependentPreset, resolveWebDelivery, loadDeliveryEvidence }) {
|
|
31
33
|
if (typeof resolveAgentFromPreset !== 'function') throw TypeError('The host preset-to-Agent resolver is required');
|
|
32
34
|
const { React, ReactDOM } = ui;
|
|
33
35
|
const { createElement: h, useMemo, useEffect, useLayoutEffect, useState, useRef } = React;
|
|
34
|
-
const {
|
|
36
|
+
const { HarnessTurn } = createHarnessComponents(React);
|
|
35
37
|
const { ConversationStatusPanel } = createStatusPanelComponents(React, ReactDOM);
|
|
36
38
|
const { MarkdownResponse } = createMarkdownComponents(React, ReactDOM);
|
|
37
39
|
const commandPane = installNativeCommandPane(ctx, { React, hostRemote });
|
|
@@ -40,7 +42,8 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
40
42
|
onOpenExternalUrl: url => { if (['http:', 'https:'].includes(new URL(url).protocol)) window.open(url, '_blank', 'noopener,noreferrer'); },
|
|
41
43
|
onOpenFileLink: onOpenFile && (({ href }) => { const target = taskWorkspaceFileTarget(href, cwd); if (target) onOpenFile(target); }) }, text) });
|
|
42
44
|
const markdownLabels = { copyCode: '复制代码', copied: '已复制', wrapLines: '自动换行', languageLabel: '代码' };
|
|
43
|
-
function TaskView({ sessionId, useHarnessEvents, useSession, useSessions, useProjection, cwd, openFile,
|
|
45
|
+
function TaskView({ sessionId, useHarnessEvents, useSession, useSessions, useProjection, cwd, openFile, openExternalLink,
|
|
46
|
+
branchAt, renderAssistantActions, turnAnchors, fallback, statusPanel }) {
|
|
44
47
|
const [variant, setVariant] = useState(() => {
|
|
45
48
|
try { const saved = localStorage.getItem('native.status-panel.variant'); return ['auto', 'mini', 'panel'].includes(saved) ? saved : 'auto'; }
|
|
46
49
|
catch { return 'auto'; }
|
|
@@ -71,6 +74,10 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
71
74
|
const error = localError ?? readSnapshot?.error;
|
|
72
75
|
const projector = useMemo(() => createSessionTaskProjector({ sessionId }), [sessionId]);
|
|
73
76
|
const tasks = useMemo(() => projector.project(eventWindow), [projector, eventWindow]);
|
|
77
|
+
const resolveDelivery = useMemo(() => resolveWebDelivery
|
|
78
|
+
? (delivery, signal) => resolveWebDelivery(sessionId, delivery, signal) : undefined, [sessionId]);
|
|
79
|
+
const loadEvidence = useMemo(() => loadDeliveryEvidence
|
|
80
|
+
? (seq, signal) => loadDeliveryEvidence(sessionId, seq, signal) : undefined, [sessionId]);
|
|
74
81
|
useEffect(() => {
|
|
75
82
|
let active = true;
|
|
76
83
|
setProjectionError(null);
|
|
@@ -84,7 +91,7 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
84
91
|
const controller = new AbortController();
|
|
85
92
|
const generation = ++routeGeneration.current;
|
|
86
93
|
setRoute({ key: routeKey, kind: 'loading', agentId: null, generation }); setError(null);
|
|
87
|
-
if (routeReady) void resolveNativeRuntimeRoute({ hostRemote, presetId, resolveAgentFromPreset, signal: controller.signal })
|
|
94
|
+
if (routeReady) void resolveNativeRuntimeRoute({ hostRemote, presetId, resolveAgentFromPreset, isIndependentPreset, signal: controller.signal })
|
|
88
95
|
.then(next => { if (!controller.signal.aborted) setRoute({ ...next, key: routeKey, generation }); })
|
|
89
96
|
.catch(failure => { if (!controller.signal.aborted) setRoute({ key: routeKey, kind: 'error', agentId: null, generation,
|
|
90
97
|
error: failure.message || '无法读取当前会话的运行时' }); });
|
|
@@ -110,7 +117,9 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
110
117
|
setCommandObservations([]);
|
|
111
118
|
if (nativeAgent) return commandPane.subscribe({ agentId: nativeAgent, sessionId }, setCommandObservations);
|
|
112
119
|
}, [nativeAgent, sessionId]);
|
|
113
|
-
const
|
|
120
|
+
const engineRoute = route.key === routeKey && route.kind === 'engine';
|
|
121
|
+
const panelModel = useMemo(() => engineRoute ? engineStatusPanelModel(tasks, running)
|
|
122
|
+
: nativeStatusPanelModel(status, childTasks, commandObservations), [engineRoute, tasks, running, status, childTasks, commandObservations]);
|
|
114
123
|
useEffect(() => {
|
|
115
124
|
if (nativeAgent) for (const terminal of panelModel.terminals)
|
|
116
125
|
commandPane.register({ ...terminal, agentId: nativeAgent, sessionId });
|
|
@@ -121,7 +130,8 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
121
130
|
if (!target) { setError('文件链接不在执行工作区或位置无效'); return; }
|
|
122
131
|
void Promise.resolve(openFile(target.path)).catch(failure => setError(failure.message || '无法打开文件'));
|
|
123
132
|
};
|
|
124
|
-
const panelVisible = nativeAgent && (panelModel.git || panelModel.plan
|
|
133
|
+
const panelVisible = (nativeAgent || engineRoute) && Boolean(panelModel.git || panelModel.plan
|
|
134
|
+
|| panelModel.agents.length || panelModel.terminals.length || panelModel.isRunning);
|
|
125
135
|
useLayoutEffect(() => {
|
|
126
136
|
// The presentation owns the summary seat while routing/loading too.
|
|
127
137
|
// Lack of polled data is not permission to paint the resident Todo dock.
|
|
@@ -147,7 +157,7 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
147
157
|
if (route.kind === 'error') return h('div', { role: 'alert', 'data-testid': 'task-runtime-error' },
|
|
148
158
|
h('p', null, route.error), h('button', { type: 'button', onClick: () => setRouteAttempt(value => value + 1) }, '重试加载'));
|
|
149
159
|
if (route.kind === 'other') return fallback;
|
|
150
|
-
if (!observation) return readSnapshot?.phase === 'error'
|
|
160
|
+
if (route.kind === 'native' && !observation) return readSnapshot?.phase === 'error'
|
|
151
161
|
? h('div', { role: 'alert', 'data-testid': 'task-observation-error' }, h('p', null, readSnapshot.error),
|
|
152
162
|
h('button', { type: 'button', onClick: () => void readerRef.current?.refresh() }, '重试加载任务过程'))
|
|
153
163
|
: h('div', { role: 'status', 'data-testid': 'task-observation-loading' }, '正在同步任务过程…');
|
|
@@ -160,16 +170,19 @@ export function installTaskTimeline(ctx, { ui, hostRemote, resolveAgentFromPrese
|
|
|
160
170
|
onOpenSubagent: openSubagent,
|
|
161
171
|
onOpenTerminal: terminal => commandPane.open({ ...terminal, agentId: nativeAgent, sessionId }),
|
|
162
172
|
onOpenSubagentDirectory: () => childPane.openDirectory({ agentId: nativeAgent, parentSessionId: sessionId }) })), statusPanel.target) : null,
|
|
163
|
-
...presented.map(({ turn, state }) => h(
|
|
164
|
-
state,
|
|
173
|
+
...presented.map(({ turn, state, reply, deliveries, deliverySeq }) => h(HarnessTurn, { key: turn,
|
|
174
|
+
state, reply, onBranch: branchAt, assistantActions: reply?.messageId ? renderAssistantActions?.(reply.messageId) : null,
|
|
175
|
+
deliveries, resolveWebDelivery: resolveDelivery, deliverySeq, loadDeliveryEvidence: loadEvidence,
|
|
176
|
+
containerProps: { 'data-chat-anchor-key': turnAnchors?.get(turn), 'data-chat-paging-anchor': true },
|
|
177
|
+
labels, locale: 'zh-CN', showPlanDock: !statusPanel, theme: theme.active.colorScheme,
|
|
165
178
|
workspaceRoot: executionRoot,
|
|
166
179
|
onOpenFile: ({ path }) => openWorkspaceFile(path),
|
|
167
180
|
onOpenSubagent: openSubagent,
|
|
168
|
-
onCopy: text =>
|
|
181
|
+
onCopy: text => navigator.clipboard.writeText(text),
|
|
169
182
|
renderText: (text, { streaming }) => h(MarkdownResponse, { streaming, theme: theme.active.colorScheme, scopeKey: sessionId + ':' + executionRoot,
|
|
170
183
|
labels: markdownLabels,
|
|
171
184
|
onCopyCode: text => navigator.clipboard.writeText(text),
|
|
172
|
-
onOpenExternalUrl: url => { if (['http:', 'https:'].includes(new URL(url).protocol)) window.open(url, '_blank', 'noopener,noreferrer'); },
|
|
185
|
+
onOpenExternalUrl: openExternalLink ?? (url => { if (['http:', 'https:'].includes(new URL(url).protocol)) window.open(url, '_blank', 'noopener,noreferrer'); }),
|
|
173
186
|
onOpenFileLink: ({ href }) => openWorkspaceFile(href) }, text) })),
|
|
174
187
|
...(pending ?? []).filter(item => item.placement === 'transcript').map(item => h('p', { key: item.requestId, 'aria-label': '待发送输入' }, item.text)),
|
|
175
188
|
error ? h('p', { role: 'alert' }, error) : null,
|
package/src/index.mjs
CHANGED
|
@@ -49,4 +49,4 @@ export { toolIdentity, toolConversationVisible, localizedToolTitle } from './too
|
|
|
49
49
|
|
|
50
50
|
// React binding. Imported lazily-safe only because this barrel re-exports it;
|
|
51
51
|
// hosts that do not need React should import the subpaths directly.
|
|
52
|
-
export { HarnessTimeline } from "./components.mjs";
|
|
52
|
+
export { HarnessTimeline, HarnessTurn } from "./components.mjs";
|
package/src/project.mjs
CHANGED
|
@@ -69,8 +69,8 @@ export function isTerminal(state) {
|
|
|
69
69
|
export function planProgress(state) {
|
|
70
70
|
const plan = state?.plan;
|
|
71
71
|
if (!Array.isArray(plan) || !plan.length) return null;
|
|
72
|
-
const total = plan.length;
|
|
73
|
-
const completed = plan.filter(item => item.status === "completed").length;
|
|
72
|
+
const total = state.planSummary?.totalCount ?? plan.length;
|
|
73
|
+
const completed = state.planSummary?.completedCount ?? plan.filter(item => item.status === "completed").length;
|
|
74
74
|
const inProgress = plan.find(item => item.status === "in_progress");
|
|
75
75
|
return {
|
|
76
76
|
total,
|
package/src/protocol.mjs
CHANGED
|
@@ -21,6 +21,7 @@ export const EventType = Object.freeze({
|
|
|
21
21
|
TaskStarted: "task.started",
|
|
22
22
|
TaskState: "task.state",
|
|
23
23
|
TaskFinished: "task.finished",
|
|
24
|
+
ModelRequest: "model.request",
|
|
24
25
|
TextDelta: "text.delta",
|
|
25
26
|
TextDone: "text.done",
|
|
26
27
|
ThinkingStart: "thinking.start",
|
|
@@ -162,6 +163,10 @@ function normalizePayload(type, event) {
|
|
|
162
163
|
...(hostTime(event.startedAt) !== null ? { startedAt: event.startedAt } : {}) };
|
|
163
164
|
case EventType.TaskState:
|
|
164
165
|
return { state: requiredChoice(event.state, TASK_STATES, "task state"), reason: str(event.reason) || null, message: str(event.message) || null };
|
|
166
|
+
case EventType.ModelRequest:
|
|
167
|
+
if (typeof event.active !== "boolean") throw new TypeError("model request requires an active flag");
|
|
168
|
+
return { active: event.active, itemId: str(event.itemId), ...(event.retry === true ? { retry: true } : {}),
|
|
169
|
+
...(event.purpose === "compaction" ? { purpose: "compaction" } : {}) };
|
|
165
170
|
case EventType.TaskFinished: {
|
|
166
171
|
const outcome = requiredChoice(event.outcome, TASK_OUTCOMES, "task outcome");
|
|
167
172
|
if (event.executionState !== undefined && (event.executionState !== TaskState.Interrupted || outcome !== TaskOutcome.Unverified))
|
|
@@ -223,7 +228,8 @@ function normalizePayload(type, event) {
|
|
|
223
228
|
after: { kind: marker.after.kind, ...(marker.after.id ? { id: marker.after.id } : {}) } } };
|
|
224
229
|
}
|
|
225
230
|
case EventType.PlanUpdated:
|
|
226
|
-
return { items: Array.isArray(event.items) ? event.items.map(normalizePlanItem).filter(Boolean) : []
|
|
231
|
+
return { items: Array.isArray(event.items) ? event.items.map(normalizePlanItem).filter(Boolean) : [],
|
|
232
|
+
completedCount: event.completedCount, totalCount: event.totalCount };
|
|
227
233
|
default:
|
|
228
234
|
return {};
|
|
229
235
|
}
|