@inupedia/spotlight-vue 0.6.0 → 0.7.1

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.
@@ -1,385 +1,193 @@
1
- import { serializeSkillsForRemote as F } from "@inupedia/spotlight-client";
2
- import { useAgentSessionStore as L } from "../session/agentSession.js";
3
- import { useSpotlightMemoryPreferenceStore as J } from "../store/memoryPreferenceStore.js";
4
- import { useSpotlightRuntimeStore as j } from "../store/runtimeStore.js";
5
- import { SPOTLIGHT_PIPELINE_STEP_IDS as r } from "../store/pipeline/constants.js";
6
- import { isLoopPlanningChunk as B, splitIntentStepContent as W } from "../store/pipeline/displayText.js";
7
- import { toolLaneStepId as M, resolveToolLane as U, toolLaneStepLabel as z } from "../store/pipeline/toolLane.js";
8
- import { getSpotlightConfig as E } from "../plugin.js";
9
- import { getSkillsPoolForRun as G } from "../skills/index.js";
10
- import { executeRemoteHostTool as V, ensureHostToolsManifest as A } from "./hostToolRunner.js";
11
- import { getSpotlightServerBase as T, buildSpotlightJsonHeaders as w, getSpotlightProjectId as Y } from "./httpConfig.js";
12
- import { ensureSpotlightMeta as K } from "./meta.js";
13
- const N = /* @__PURE__ */ new WeakMap();
14
- function Q(t) {
15
- return t.type !== "host_action_request" && t.type !== "run_completed" && t.type !== "run_error" && t.type !== "run_status" && t.type !== "ping" && t.type !== "memory_decision";
1
+ import { useAgentSessionStore as g } from "../session/agentSession.js";
2
+ import { useSpotlightMemoryPreferenceStore as C } from "../store/memoryPreferenceStore.js";
3
+ import { useSpotlightRuntimeStore as P } from "../store/runtimeStore.js";
4
+ import { SPOTLIGHT_PIPELINE_STEP_IDS as i } from "../store/pipeline/constants.js";
5
+ import { toolLaneStepId as h, resolveToolLane as b, toolLaneStepLabel as x } from "../store/pipeline/toolLane.js";
6
+ import { getSpotlightAppClient as k, getSpotlightConfig as S } from "../plugin.js";
7
+ import { executeRemoteHostTool as E, ensureHostToolsManifest as A } from "./hostToolRunner.js";
8
+ import { getSpotlightProjectId as _ } from "./httpConfig.js";
9
+ import { ensureSpotlightMeta as L } from "./meta.js";
10
+ const R = /* @__PURE__ */ new WeakMap();
11
+ function f(e, o, r) {
12
+ const t = e.getSteps().find((a) => a.id === o);
13
+ if (t) return t;
14
+ const n = { id: o, label: r, status: "pending" };
15
+ return e.setSteps([...e.getSteps(), n]), n;
16
16
  }
17
- function u(t, e, o) {
18
- const s = t.getSteps().find((a) => a.id === e);
19
- if (s) return s;
20
- const n = { id: e, label: o, status: "pending" };
21
- return t.setSteps([...t.getSteps(), n]), n;
22
- }
23
- function O() {
24
- return new Promise((t) => {
25
- requestAnimationFrame(() => t());
17
+ function q() {
18
+ return new Promise((e) => {
19
+ requestAnimationFrame(() => e());
26
20
  });
27
21
  }
28
- function X(t) {
29
- return Array.isArray(t) ? t.flatMap((o, s) => {
30
- if (!o || typeof o != "object") return [];
31
- const n = o, a = typeof n.content == "string" ? n.content.trim() : "";
22
+ function M(e) {
23
+ return Array.isArray(e) ? e.flatMap((r, t) => {
24
+ if (!r || typeof r != "object") return [];
25
+ const n = r, a = typeof n.content == "string" ? n.content.trim() : "";
32
26
  if (!a) return [];
33
- const i = typeof n.title == "string" && n.title.trim() || typeof n.url == "string" && n.url.trim() || `资料 ${s + 1}`, f = typeof n.url == "string" ? n.url.trim() : "";
34
- return [[i, f && f !== i ? f : "", a].filter(Boolean).join(`
27
+ const c = typeof n.title == "string" && n.title.trim() || typeof n.url == "string" && n.url.trim() || `资料 ${t + 1}`, u = typeof n.url == "string" ? n.url.trim() : "";
28
+ return [[c, u && u !== c ? u : "", a].filter(Boolean).join(`
35
29
  `)];
36
30
  }).join(`
37
31
 
38
32
  `) : "";
39
33
  }
40
- function Z(t) {
41
- const e = X(t.output);
42
- if (e) return e;
43
- const o = t.summary?.trim();
44
- if (o && o.length > 48 && !o.startsWith("{") && !o.startsWith("["))
45
- return o;
46
- if (t.output != null && typeof t.output == "object")
47
- try {
48
- const s = JSON.stringify(t.output, null, 2);
49
- if (s && s !== "{}") return s;
50
- } catch {
51
- }
52
- return o || "";
53
- }
54
- function v(t) {
55
- const e = Z(t.result);
56
- return {
57
- id: t.result.call.id,
58
- name: t.result.call.name,
59
- displayName: t.result.call.displayName,
60
- argsText: JSON.stringify(t.result.call.input ?? {}, null, 2),
61
- resultText: e,
62
- summary: t.result.summary,
63
- errorCode: t.result.errorCode,
64
- trace: t.result.trace,
65
- status: t.result.success ? "done" : "error"
66
- };
67
- }
68
- function tt(t) {
69
- return {
70
- id: t.call.id,
71
- name: t.call.name,
72
- displayName: t.call.displayName,
73
- argsText: JSON.stringify(t.call.input ?? {}, null, 2),
74
- status: "running"
75
- };
76
- }
77
- function et(t, e) {
78
- const o = e.success ? "前端操作已执行。" : e.error || "前端操作执行失败。";
34
+ function O(e, o) {
35
+ const r = o.success ? "前端操作已执行。" : o.error || "前端操作执行失败。";
79
36
  return {
80
- id: t.id,
81
- name: t.name,
82
- displayName: t.displayName,
83
- argsText: JSON.stringify(t.input ?? {}, null, 2),
84
- resultText: o,
85
- summary: o,
86
- errorCode: e.errorCode,
87
- trace: e.trace,
88
- status: e.success ? "done" : "error"
37
+ id: e.id,
38
+ name: e.name,
39
+ displayName: e.displayName,
40
+ argsText: JSON.stringify(e.input ?? {}, null, 2),
41
+ resultText: r,
42
+ summary: r,
43
+ errorCode: o.errorCode,
44
+ trace: o.trace,
45
+ status: o.success ? "done" : "error"
89
46
  };
90
47
  }
91
- function st(t, e) {
92
- return U(t, e?.sideEffectByName?.get(t));
48
+ function j(e, o) {
49
+ return b(e, o?.sideEffectByName?.get(e));
93
50
  }
94
- function d(t, e, o) {
95
- const s = t.getSteps().find((n) => n.id === e);
96
- !s || s.status === "done" || s.status === "error" || t.setStep(e, "done", s.content ?? o);
51
+ function p(e, o, r) {
52
+ const t = e.getSteps().find((n) => n.id === o);
53
+ !t || t.status === "done" || t.status === "error" || e.setStep(o, "done", t.content ?? r);
97
54
  }
98
- function R(t, e) {
99
- d(t, r.understand);
100
- const o = M(e), s = z(e);
101
- u(t, o, s);
102
- const n = t.getSteps().find((a) => a.id === o);
103
- !n || n.status === "active" || n.status === "done" || t.setStep(o, "active", n.content);
55
+ function H(e, o) {
56
+ p(e, i.understand);
57
+ const r = h(o), t = x(o);
58
+ f(e, r, t);
59
+ const n = e.getSteps().find((a) => a.id === r);
60
+ !n || n.status === "active" || n.status === "done" || e.setStep(r, "active", n.content);
104
61
  }
105
- function S(t, e, o) {
106
- const s = st(e, o);
107
- return R(t, s), M(s);
108
- }
109
- function nt(t, e, o) {
110
- const s = S(t, e.name, o);
111
- t.appendToolCallsToStep(s, [
112
- {
113
- id: e.id,
114
- name: e.name,
115
- displayName: e.displayName,
116
- argsText: JSON.stringify(e.input ?? {}, null, 2),
117
- status: "running"
118
- }
119
- ]);
62
+ function I(e, o, r) {
63
+ const t = j(o, r);
64
+ return H(e, t), h(t);
120
65
  }
121
- function ot(t, e, o, s) {
122
- const n = S(t, e.name, s);
123
- t.appendToolCallsToStep(n, [et(e, o)]);
66
+ function B(e, o, r, t) {
67
+ const n = I(e, o.name, t);
68
+ e.appendToolCallsToStep(n, [O(o, r)]);
124
69
  }
125
- function b(t, e) {
126
- return e || (t === r.gather ? "获取信息" : t === r.act ? "操作页面" : t === r.answer ? "回答" : t === r.understand ? "理解问题" : t === r.tool ? "获取信息" : t);
70
+ function v(e, o, r, t, n) {
71
+ f(e, o, r), e.setStep(o, t, n);
127
72
  }
128
- function y(t, e, o, s, n) {
129
- u(t, e, o), t.setStep(e, s, n);
73
+ function D(e) {
74
+ const o = e.status === "completed" ? "done" : e.status === "failed" ? "error" : "running";
75
+ return e.type === "knowledge_search" ? {
76
+ id: e.id,
77
+ name: e.tool,
78
+ displayName: e.displayName,
79
+ argsText: JSON.stringify({ query: e.query }, null, 2),
80
+ resultText: M(e.result),
81
+ summary: e.summary,
82
+ status: o
83
+ } : {
84
+ id: e.id,
85
+ name: e.tool,
86
+ displayName: e.displayName,
87
+ argsText: JSON.stringify(e.arguments ?? {}, null, 2),
88
+ resultText: e.result === void 0 ? void 0 : typeof e.result == "string" ? e.result : JSON.stringify(e.result, null, 2),
89
+ summary: e.summary ?? e.error?.message,
90
+ errorCode: e.error?.code,
91
+ trace: e.trace,
92
+ status: o
93
+ };
130
94
  }
131
- function rt(t, e) {
132
- const o = e.summary?.trim();
133
- switch (e.phase) {
134
- case "routing":
135
- case "analyzing":
136
- y(
137
- t,
138
- r.understand,
139
- "理解问题",
140
- "active",
141
- o ?? "正在分析用户意图。"
142
- );
143
- return;
144
- case "router_done":
145
- y(
146
- t,
147
- r.understand,
95
+ async function F(e, o, r) {
96
+ if (o.type !== "ping") {
97
+ if (o.type === "turn.started") {
98
+ v(
99
+ e,
100
+ i.understand,
148
101
  "理解问题",
149
- "done",
150
- o ?? "意图分析已完成。"
151
- );
152
- return;
153
- case "knowledge_agent_start":
154
- d(t, r.understand), y(
155
- t,
156
- r.gather,
157
- "获取信息",
158
102
  "active",
159
- o ?? "正在检索资料。"
160
- );
161
- return;
162
- case "knowledge_agent_done":
163
- d(
164
- t,
165
- r.gather,
166
- o ?? "资料已就绪。"
167
- );
168
- return;
169
- case "action_agent_start":
170
- d(t, r.understand);
171
- return;
172
- case "action_agent_done":
173
- d(t, r.gather), d(
174
- t,
175
- r.act,
176
- o ?? "页面操作已完成。"
177
- );
178
- return;
179
- case "memory_replay":
180
- y(
181
- t,
182
- r.understand,
183
- "理解问题",
184
- "done",
185
- o ?? "已复用项目记忆,跳过本轮检索。"
103
+ "正在理解您的问题。"
186
104
  );
187
105
  return;
188
- default:
189
- return;
190
- }
191
- }
192
- async function at(t, e, o) {
193
- if (e.type !== "ping") {
194
- if (e.type === "step_sync")
195
- t.setSteps(
196
- e.steps.map((s) => ({
197
- id: s.id,
198
- label: s.label,
199
- status: s.status,
200
- content: t.getSteps().find((n) => n.id === s.id)?.content
201
- }))
202
- );
203
- else if (e.type === "step_status")
204
- u(t, e.stepId, e.label ?? e.stepId), t.setStep(e.stepId, e.status, e.content);
205
- else if (e.type === "step_content") {
206
- let s = e.stepId, n = e.content;
207
- if ((s === r.intent || s === r.understand) && B(n))
208
- s = r.gather;
209
- else if ((s === r.intent || s === r.understand) && e.mode === "replace") {
210
- const { intent: a, misplacedPlanning: i } = W(n);
211
- n = a, i.trim() && (u(t, r.gather, "获取信息"), t.appendChunkToStep(
212
- r.gather,
213
- i
214
- ));
215
- }
216
- if (u(t, s, b(s, e.label)), e.mode === "replace")
217
- t.setStep(
218
- s,
219
- t.getSteps().find((a) => a.id === s)?.status ?? "active",
220
- n
221
- );
222
- else {
223
- if (s === r.tool || s === r.gather || s === r.act) {
224
- const a = s === r.act ? "act" : "gather";
225
- R(t, a);
106
+ }
107
+ if (o.type === "item.started" || o.type === "item.updated" || o.type === "item.completed") {
108
+ const t = o.item;
109
+ if (t.type === "reasoning") {
110
+ if (t.category === "routing" || t.category === "memory")
111
+ v(
112
+ e,
113
+ i.understand,
114
+ "理解问题",
115
+ o.type === "item.completed" ? "done" : "active",
116
+ t.summary
117
+ );
118
+ else {
119
+ const n = /页面|操作|执行/u.test(t.summary), a = n ? i.act : i.gather;
120
+ f(e, a, n ? "操作页面" : "获取信息"), e.setStep(
121
+ a,
122
+ o.type === "item.completed" ? "done" : "active",
123
+ t.summary
124
+ );
226
125
  }
227
- t.appendChunkToStep(s, n), await O();
126
+ return;
228
127
  }
229
- } else if (e.type === "step_artifact") {
230
- const s = e.stepId === r.tool ? r.gather : e.stepId;
231
- u(t, s, b(s, e.label)), (s === r.gather || s === r.act) && R(
232
- t,
233
- s === r.act ? "act" : "gather"
234
- ), e.artifact === "tool_calls" && e.toolCalls?.length ? t.appendToolCallsToStep(s, e.toolCalls) : e.artifact === "attachments" && e.attachments?.length ? t.appendAttachmentsToStep(s, e.attachments) : e.artifact === "files" && e.files?.length ? t.appendFilesToStep(s, e.files) : e.artifact === "artifacts" && e.artifacts?.length ? t.appendArtifactsToStep(s, e.artifacts) : e.artifact === "chat_items" && e.chatItems?.length && t.appendChatItemsToStep(s, e.chatItems);
235
- } else if (e.type === "tool_start") {
236
- const s = S(t, e.call.name, o);
237
- t.appendToolCallsToStep(s, [tt(e)]);
238
- } else if (e.type === "tool_progress") {
239
- const s = S(t, e.call.name, o);
240
- t.appendToolCallsToStep(s, [
241
- {
242
- id: e.call.id,
243
- name: e.call.name,
244
- displayName: e.call.displayName,
245
- argsText: JSON.stringify(e.call.input ?? {}, null, 2),
246
- summary: e.summary,
247
- status: "running"
248
- }
249
- ]);
250
- } else if (e.type === "tool_result") {
251
- const s = S(t, e.result.call.name, o);
252
- t.appendToolCallsToStep(s, [v(e)]), e.result.attachments?.length && t.appendAttachmentsToStep(s, e.result.attachments), e.result.files?.length && t.appendFilesToStep(s, e.result.files), e.result.toolCalls?.length && t.appendToolCallsToStep(s, e.result.toolCalls);
253
- } else if (e.type === "skill_permission_request") {
254
- const { useSpotlightStore: s } = await import("../store/spotlightStore.js");
255
- s().setPendingSkillPermission({
256
- skillName: e.skillName,
257
- displayName: e.displayName,
258
- reason: e.reason,
259
- source: e.source,
260
- at: e.at
261
- });
262
- } else if (e.type === "fork_progress") {
263
- const s = r.gather;
264
- u(t, s, "获取信息"), t.appendChunkToStep(
265
- s,
266
- `
267
- [fork ${e.agentId}] 第 ${e.iteration} 轮 · ${e.phase}:${e.summary}
268
- `
269
- );
270
- } else if (e.type === "turn_transition")
271
- rt(t, e);
272
- else if (e.type === "memory_decision") {
273
- const s = {
274
- reuse: "已复用项目记忆",
275
- augment: "正在结合历史项目结论",
276
- refresh: "资料可能变化,正在重新验证",
277
- ignore: "未发现可直接使用的项目记忆"
278
- }, n = t.getSteps().find((i) => i.id === r.understand), a = e.decision.action === "reuse" || n?.status === "done" ? "done" : "active";
279
- y(
280
- t,
281
- r.understand,
282
- "理解问题",
283
- a,
284
- s[e.decision.action]
285
- );
286
- } else if (e.type === "run_status") {
287
- const s = e.detail?.trim();
288
- if (s) {
289
- const n = t.getSteps().find((a) => a.id === r.act) ? r.act : r.gather;
290
- u(t, n, b(n, null)), t.appendChunkToStep(n, `
291
- ${s}
128
+ if (t.type === "skill_use") {
129
+ const n = "skills", a = f(e, n, "使用 Skill"), c = `- ${t.displayName}${t.skill === t.displayName ? "" : `(${t.skill})`}`, u = a.content?.includes(c) ? a.content : [a.content, c].filter(Boolean).join(`
292
130
  `);
131
+ e.setStep(n, t.status === "failed" ? "error" : "done", u), g().setInvokedSkills([
132
+ ...g().invokedSkills.filter(
133
+ (d) => d.skillName !== t.skill
134
+ ),
135
+ { skillName: t.skill, invokedAt: o.at }
136
+ ]);
137
+ return;
293
138
  }
294
- } else e.type === "assistant_response" && (d(t, r.understand), d(t, r.gather), d(t, r.act), u(t, r.answer, "回答"), t.setStep(
295
- r.answer,
296
- "done",
297
- e.content.trim()
298
- ));
299
- Q(e) && t.appendExecutionEvent?.(e);
300
- }
301
- }
302
- async function it(t) {
303
- await fetch(
304
- `${T()}/v1/runs/${encodeURIComponent(t.runId)}/host-results`,
305
- {
306
- method: "POST",
307
- headers: w(),
308
- body: JSON.stringify({
309
- correlationId: t.correlationId,
310
- success: t.result.success,
311
- output: t.result.data,
312
- error: t.result.error,
313
- errorCode: t.result.errorCode,
314
- trace: t.result.trace,
315
- // Free observation: the page just changed, so tell the agent what it
316
- // looks like now instead of making it plan against the pre-call state.
317
- uiContext: E().getUiContext?.() ?? void 0
318
- }),
319
- signal: t.signal
320
- }
321
- );
322
- }
323
- function lt(t) {
324
- const e = t.split(/\n\n/u), o = e.pop() ?? "";
325
- return { events: e.flatMap((n) => {
326
- const a = n.split(/\n/u), i = a.find((c) => c.startsWith("data: "));
327
- if (!i) return [];
328
- const f = a.find((c) => c.startsWith("id: ")), p = f ? Number.parseInt(f.slice(4), 10) : Number.NaN;
329
- try {
330
- const c = JSON.parse(i.slice(6));
331
- return [Number.isFinite(p) ? { ...c, seq: p } : c];
332
- } catch {
333
- return [];
139
+ if (t.type === "tool_call" || t.type === "knowledge_search") {
140
+ const n = (t.type === "tool_call", t.tool), a = I(e, n, r);
141
+ e.appendToolCallsToStep(a, [D(t)]), (t.status === "completed" || t.status === "failed") && p(e, a);
142
+ return;
143
+ }
144
+ if (t.type === "memory") {
145
+ v(
146
+ e,
147
+ i.understand,
148
+ "理解问题",
149
+ t.action === "reuse" ? "done" : "active",
150
+ t.summary
151
+ );
152
+ return;
153
+ }
154
+ if (t.type === "agent_message") {
155
+ p(e, i.understand), p(e, i.gather), p(e, i.act), f(e, i.answer, "回答"), e.setStep(i.answer, "done", t.text.trim());
156
+ return;
157
+ }
158
+ t.type === "error" && e.setError(t.message);
159
+ return;
334
160
  }
335
- }), rest: o };
336
- }
337
- const ct = 6, ut = 400;
338
- async function dt(t, e, o) {
339
- const s = e > 0 ? `?lastEventId=${e}` : "", n = await fetch(
340
- `${T()}/v1/runs/${encodeURIComponent(t)}/events${s}`,
341
- { headers: w(), signal: o }
342
- );
343
- if (n.status === 410)
344
- throw new Error("Spotlight 后端已不再保留这次运行的记录,请重新提问。");
345
- if (!n.ok || !n.body)
346
- throw new Error(`Spotlight 后端事件流连接失败:${n.status}`);
347
- return n;
348
- }
349
- function ft(t) {
350
- return Math.min(ut * 2 ** t, 5e3);
351
- }
352
- function mt(t) {
353
- return new Promise((e) => setTimeout(e, t));
161
+ o.type === "turn.failed" && e.setError(o.error.message);
162
+ }
354
163
  }
355
- async function kt(t) {
164
+ async function ee(e) {
356
165
  await Promise.allSettled([
357
- A(),
358
- K(t)
166
+ k().initialize(e),
167
+ L(e)
359
168
  ]);
360
169
  }
361
- async function pt(t, e, o) {
362
- const s = L(), n = j(), a = J(), i = await A();
170
+ async function J(e, o, r) {
171
+ const t = g(), n = P(), a = C();
363
172
  return {
364
- hostManifest: i,
173
+ hostManifest: await A(),
365
174
  payload: {
366
- projectId: Y(),
367
- sessionId: s.sessionId,
368
- memorySubjectId: E().getMemorySubjectId?.() ?? void 0,
369
- userQuestion: t,
370
- memoryRefreshRequested: o?.forceMemoryRefresh === !0,
371
- uiContext: E().getUiContext?.() ?? {},
175
+ projectId: _(),
176
+ input: e,
177
+ memorySubjectId: S().getMemorySubjectId?.() ?? void 0,
178
+ memoryRefreshRequested: r?.forceMemoryRefresh === !0,
179
+ uiContext: S().getUiContext?.() ?? {},
372
180
  sessionState: {
373
- sessionId: s.sessionId,
374
- activeTaskId: s.activeTaskId,
375
- activeTopic: s.activeTopic,
376
- pendingTask: s.pendingTask,
377
- conversationSummary: s.conversationSummary,
378
- summarizedTurnCount: s.summarizedTurnCount,
379
- conversationHistory: s.conversationHistory,
380
- lastAssistantReply: s.getLastAssistantContent(),
381
- invokedSkills: s.invokedSkills,
382
- skillPermissionGrants: s.skillPermissionGrants,
181
+ sessionId: t.sessionId,
182
+ activeTaskId: t.activeTaskId,
183
+ activeTopic: t.activeTopic,
184
+ pendingTask: t.pendingTask,
185
+ conversationSummary: t.conversationSummary,
186
+ summarizedTurnCount: t.summarizedTurnCount,
187
+ conversationHistory: t.conversationHistory,
188
+ lastAssistantReply: t.getLastAssistantContent(),
189
+ invokedSkills: t.invokedSkills,
190
+ skillPermissionGrants: t.skillPermissionGrants,
383
191
  memoryEnabled: a.enabled,
384
192
  memoryReadEnabled: a.enabled,
385
193
  memoryWriteEnabled: !0
@@ -390,120 +198,83 @@ async function pt(t, e, o) {
390
198
  activeAction: n.activeAction,
391
199
  resumableAction: n.resumableAction,
392
200
  lastResolvedTarget: n.lastResolvedTarget
393
- },
394
- clientToolsManifestVersion: i.manifestDigest,
395
- clientToolManifest: i,
396
- skills: F(G()),
397
- frontendBuildId: i.frontendBuildId,
398
- manifestDigest: i.manifestDigest
201
+ }
399
202
  }
400
203
  };
401
204
  }
402
- async function Pt(t, e, o) {
403
- const s = T(), n = e.getSignal(), { payload: a, hostManifest: i } = await pt(
205
+ async function te(e, o, r) {
206
+ const t = o.getSignal(), { payload: n, hostManifest: a } = await J(
207
+ e,
404
208
  t,
405
- n,
406
- o
407
- ), f = new Set(i.tools.map((m) => m.name)), p = {
209
+ r
210
+ ), c = new Set(a.tools.map((s) => s.name)), u = {
408
211
  sideEffectByName: new Map(
409
- i.tools.map((m) => [m.name, m.sideEffect])
212
+ a.tools.map((s) => [s.name, s.sideEffect])
410
213
  )
411
- }, c = await fetch(`${s}/v1/runs`, {
412
- method: "POST",
413
- headers: w(),
414
- body: JSON.stringify(a),
415
- signal: n
416
- });
417
- if (!c.ok) {
418
- const m = await c.text().catch(() => "");
419
- throw new Error(
420
- `Spotlight 后端创建 run 失败:${c.status} ${m}`
421
- );
422
- }
423
- const { runId: h } = await c.json();
424
- n && (N.set(n, h), n.addEventListener(
214
+ }, d = k(), w = g(), N = await d.startThread(w.sessionId, t), y = await d.startTurn(N.id, n, t);
215
+ t && (R.set(t, y.id), t.addEventListener(
425
216
  "abort",
426
217
  () => {
427
- q(h);
218
+ d.cancelTurn(y.id);
428
219
  },
429
220
  { once: !0 }
430
221
  ));
431
- let k = 0, C = 0;
432
- for (; ; ) {
433
- const P = (await dt(h, k, n)).body.getReader(), D = new TextDecoder();
434
- let I = "", _ = !1;
435
- try {
436
- for (; ; ) {
437
- const { done: g, value: H } = await P.read();
438
- if (g) {
439
- _ = !0;
440
- break;
441
- }
442
- I += D.decode(H, { stream: !0 });
443
- const x = lt(I);
444
- I = x.rest;
445
- for (const l of x.events) {
446
- if (typeof l.seq == "number" && (k = l.seq), l.type === "host_action_request") {
447
- nt(e, l.request.call, p);
448
- const $ = await V(l.request.call, e, {
449
- allowedHostNames: f,
450
- hostEffect: l.request.hostEffect
451
- });
452
- ot(e, l.request.call, $, p), await it({
453
- runId: h,
454
- correlationId: l.request.correlationId,
455
- result: $,
456
- signal: n
457
- });
458
- continue;
459
- }
460
- if (l.type === "run_error")
461
- throw new Error(l.error);
462
- if (await at(e, l, p), await O(), l.type === "run_completed")
463
- return l.sessionPatch && L().applySessionPatch(l.sessionPatch), {
464
- command: null,
465
- memoryReplay: l.memoryReplay ?? null,
466
- memoryDecision: l.memoryDecision ?? null,
467
- assistantReply: l.assistantReply
468
- };
469
- }
470
- }
471
- } catch (g) {
472
- if (n?.aborted || !gt(g)) throw g;
473
- _ = !0;
474
- } finally {
475
- P.releaseLock();
222
+ for await (const s of d.streamTurn(y.id, t)) {
223
+ if (await F(o, s, u), (s.type === "item.started" || s.type === "item.updated") && s.item.type === "tool_call" && s.item.status === "waiting_for_client" && s.item.clientRequest) {
224
+ const l = {
225
+ id: s.item.id,
226
+ name: s.item.tool,
227
+ input: s.item.arguments,
228
+ displayName: s.item.displayName
229
+ }, m = !(s.item.clientRequest.approvalRequired === !0) || !!await S().approveTool?.({
230
+ name: l.name,
231
+ displayName: l.displayName,
232
+ input: l.input,
233
+ reason: s.item.clientRequest.approvalReason
234
+ }) ? await E(l, o, { allowedHostNames: c }) : {
235
+ success: !1,
236
+ error: "Tool execution was not approved",
237
+ errorCode: "TOOL_APPROVAL_REQUIRED",
238
+ trace: []
239
+ };
240
+ B(o, l, m, u), await d.submitToolResult(y.id, {
241
+ correlationId: s.item.clientRequest.correlationId,
242
+ success: m.success,
243
+ output: m.data,
244
+ error: m.error,
245
+ errorCode: m.errorCode,
246
+ trace: m.trace,
247
+ uiContext: S().getUiContext?.() ?? void 0
248
+ }, t);
249
+ continue;
250
+ }
251
+ if (await q(), s.type === "turn.failed")
252
+ throw new Error(s.error.message);
253
+ if (s.type === "turn.completed") {
254
+ const l = s.metadata ?? {}, T = l.sessionPatch;
255
+ return T && w.applySessionPatch(T), {
256
+ command: null,
257
+ memoryReplay: l.memoryReplay ?? null,
258
+ memoryDecision: l.memoryDecision ?? null,
259
+ assistantReply: s.finalResponse
260
+ };
476
261
  }
477
- if (!_ || n?.aborted) return { command: null };
478
- if (C += 1, C > ct)
479
- throw new Error("Spotlight 后端事件流多次重连失败,请重试。");
480
- await mt(ft(C - 1));
481
262
  }
263
+ return { command: null };
482
264
  }
483
- function gt(t) {
484
- return t instanceof TypeError || t instanceof DOMException;
485
- }
486
- async function q(t) {
487
- await fetch(
488
- `${T()}/v1/runs/${encodeURIComponent(t)}`,
489
- {
490
- method: "DELETE",
491
- headers: w()
492
- }
493
- );
265
+ async function $(e) {
266
+ await k().cancelTurn(e);
494
267
  }
495
- function xt(t) {
496
- if (!t) return;
497
- const e = N.get(t);
498
- e && (N.delete(t), q(e));
268
+ function oe(e) {
269
+ if (!e) return;
270
+ const o = R.get(e);
271
+ o && (R.delete(e), $(o));
499
272
  }
500
273
  export {
501
- rt as applyLangGraphTransition,
502
- at as applyRemoteEvent,
503
- nt as beginHostToolCall,
504
- q as cancelRemoteSpotlightRun,
505
- xt as cancelRemoteSpotlightRunForSignal,
506
- Pt as runRemoteSpotlightPipeline,
507
- ot as settleHostToolCall,
508
- kt as warmupSpotlightRemoteContext
274
+ F as applyLifecycleEvent,
275
+ $ as cancelRemoteSpotlightRun,
276
+ oe as cancelRemoteSpotlightRunForSignal,
277
+ te as runRemoteSpotlightPipeline,
278
+ B as settleHostToolCall,
279
+ ee as warmupSpotlightRemoteContext
509
280
  };