@inupedia/spotlight-vue 0.6.0 → 0.7.0

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,387 +1,197 @@
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";
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" };
1
+ import { serializeSkillsForRemote as C } from "@inupedia/spotlight-client";
2
+ import { useAgentSessionStore as g } from "../session/agentSession.js";
3
+ import { useSpotlightMemoryPreferenceStore as N } from "../store/memoryPreferenceStore.js";
4
+ import { useSpotlightRuntimeStore as P } from "../store/runtimeStore.js";
5
+ import { SPOTLIGHT_PIPELINE_STEP_IDS as l } from "../store/pipeline/constants.js";
6
+ import { toolLaneStepId as R, resolveToolLane as b, toolLaneStepLabel as x } from "../store/pipeline/toolLane.js";
7
+ import { getSpotlightAppClient as v, getSpotlightConfig as T } from "../plugin.js";
8
+ import { getSkillsPoolForRun as E } from "../skills/index.js";
9
+ import { executeRemoteHostTool as A, ensureHostToolsManifest as M } from "./hostToolRunner.js";
10
+ import { getSpotlightProjectId as _ } from "./httpConfig.js";
11
+ import { ensureSpotlightMeta as L } from "./meta.js";
12
+ const k = /* @__PURE__ */ new WeakMap();
13
+ function f(t, o, s) {
14
+ const e = t.getSteps().find((r) => r.id === o);
15
+ if (e) return e;
16
+ const n = { id: o, label: s, status: "pending" };
21
17
  return t.setSteps([...t.getSteps(), n]), n;
22
18
  }
23
- function O() {
19
+ function j() {
24
20
  return new Promise((t) => {
25
21
  requestAnimationFrame(() => t());
26
22
  });
27
23
  }
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() : "";
32
- 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(`
24
+ function D(t) {
25
+ return Array.isArray(t) ? t.flatMap((s, e) => {
26
+ if (!s || typeof s != "object") return [];
27
+ const n = s, r = typeof n.content == "string" ? n.content.trim() : "";
28
+ if (!r) return [];
29
+ const a = typeof n.title == "string" && n.title.trim() || typeof n.url == "string" && n.url.trim() || `资料 ${e + 1}`, u = typeof n.url == "string" ? n.url.trim() : "";
30
+ return [[a, u && u !== a ? u : "", r].filter(Boolean).join(`
35
31
  `)];
36
32
  }).join(`
37
33
 
38
34
  `) : "";
39
35
  }
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 || "前端操作执行失败。";
36
+ function H(t, o) {
37
+ const s = o.success ? "前端操作已执行。" : o.error || "前端操作执行失败。";
79
38
  return {
80
39
  id: t.id,
81
40
  name: t.name,
82
41
  displayName: t.displayName,
83
42
  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"
43
+ resultText: s,
44
+ summary: s,
45
+ errorCode: o.errorCode,
46
+ trace: o.trace,
47
+ status: o.success ? "done" : "error"
89
48
  };
90
49
  }
91
- function st(t, e) {
92
- return U(t, e?.sideEffectByName?.get(t));
50
+ function B(t, o) {
51
+ return b(t, o?.sideEffectByName?.get(t));
93
52
  }
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);
53
+ function p(t, o, s) {
54
+ const e = t.getSteps().find((n) => n.id === o);
55
+ !e || e.status === "done" || e.status === "error" || t.setStep(o, "done", e.content ?? s);
97
56
  }
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);
57
+ function F(t, o) {
58
+ p(t, l.understand);
59
+ const s = R(o), e = x(o);
60
+ f(t, s, e);
61
+ const n = t.getSteps().find((r) => r.id === s);
62
+ !n || n.status === "active" || n.status === "done" || t.setStep(s, "active", n.content);
104
63
  }
105
- function S(t, e, o) {
106
- const s = st(e, o);
107
- return R(t, s), M(s);
64
+ function h(t, o, s) {
65
+ const e = B(o, s);
66
+ return F(t, e), R(e);
108
67
  }
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
- ]);
68
+ function q(t, o, s, e) {
69
+ const n = h(t, o.name, e);
70
+ t.appendToolCallsToStep(n, [H(o, s)]);
120
71
  }
121
- function ot(t, e, o, s) {
122
- const n = S(t, e.name, s);
123
- t.appendToolCallsToStep(n, [et(e, o)]);
72
+ function S(t, o, s, e, n) {
73
+ f(t, o, s), t.setStep(o, e, n);
124
74
  }
125
- function b(t, e) {
126
- return e || (t === r.gather ? "获取信息" : t === r.act ? "操作页面" : t === r.answer ? "回答" : t === r.understand ? "理解问题" : t === r.tool ? "获取信息" : t);
127
- }
128
- function y(t, e, o, s, n) {
129
- u(t, e, o), t.setStep(e, s, n);
75
+ function O(t) {
76
+ const o = t.status === "completed" ? "done" : t.status === "failed" ? "error" : "running";
77
+ return t.type === "knowledge_search" ? {
78
+ id: t.id,
79
+ name: t.tool,
80
+ displayName: t.displayName,
81
+ argsText: JSON.stringify({ query: t.query }, null, 2),
82
+ resultText: D(t.result),
83
+ summary: t.summary,
84
+ status: o
85
+ } : {
86
+ id: t.id,
87
+ name: t.tool,
88
+ displayName: t.displayName,
89
+ argsText: JSON.stringify(t.arguments ?? {}, null, 2),
90
+ resultText: t.result === void 0 ? void 0 : typeof t.result == "string" ? t.result : JSON.stringify(t.result, null, 2),
91
+ summary: t.summary ?? t.error?.message,
92
+ errorCode: t.error?.code,
93
+ trace: t.trace,
94
+ status: o
95
+ };
130
96
  }
131
- function rt(t, e) {
132
- const o = e.summary?.trim();
133
- switch (e.phase) {
134
- case "routing":
135
- case "analyzing":
136
- y(
97
+ async function z(t, o, s) {
98
+ if (o.type !== "ping") {
99
+ if (o.type === "turn.started") {
100
+ S(
137
101
  t,
138
- r.understand,
102
+ l.understand,
139
103
  "理解问题",
140
104
  "active",
141
- o ?? "正在分析用户意图。"
142
- );
143
- return;
144
- case "router_done":
145
- y(
146
- t,
147
- r.understand,
148
- "理解问题",
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
- "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 ?? "已复用项目记忆,跳过本轮检索。"
105
+ "正在理解您的问题。"
186
106
  );
187
107
  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);
108
+ }
109
+ if (o.type === "item.started" || o.type === "item.updated" || o.type === "item.completed") {
110
+ const e = o.item;
111
+ if (e.type === "reasoning") {
112
+ if (e.category === "routing" || e.category === "memory")
113
+ S(
114
+ t,
115
+ l.understand,
116
+ "理解问题",
117
+ o.type === "item.completed" ? "done" : "active",
118
+ e.summary
119
+ );
120
+ else {
121
+ const n = /页面|操作|执行/u.test(e.summary), r = n ? l.act : l.gather;
122
+ f(t, r, n ? "操作页面" : "获取信息"), t.setStep(
123
+ r,
124
+ o.type === "item.completed" ? "done" : "active",
125
+ e.summary
126
+ );
226
127
  }
227
- t.appendChunkToStep(s, n), await O();
128
+ return;
228
129
  }
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}
130
+ if (e.type === "skill_use") {
131
+ const n = "skills", r = f(t, n, "使用 Skill"), a = `- ${e.displayName}${e.skill === e.displayName ? "" : `(${e.skill})`}`, u = r.content?.includes(a) ? r.content : [r.content, a].filter(Boolean).join(`
292
132
  `);
133
+ t.setStep(n, e.status === "failed" ? "error" : "done", u), g().setInvokedSkills([
134
+ ...g().invokedSkills.filter(
135
+ (m) => m.skillName !== e.skill
136
+ ),
137
+ { skillName: e.skill, invokedAt: o.at }
138
+ ]);
139
+ return;
293
140
  }
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 [];
141
+ if (e.type === "tool_call" || e.type === "knowledge_search") {
142
+ const n = (e.type === "tool_call", e.tool), r = h(t, n, s);
143
+ t.appendToolCallsToStep(r, [O(e)]), (e.status === "completed" || e.status === "failed") && p(t, r);
144
+ return;
145
+ }
146
+ if (e.type === "memory") {
147
+ S(
148
+ t,
149
+ l.understand,
150
+ "理解问题",
151
+ e.action === "reuse" ? "done" : "active",
152
+ e.summary
153
+ );
154
+ return;
155
+ }
156
+ if (e.type === "agent_message") {
157
+ p(t, l.understand), p(t, l.gather), p(t, l.act), f(t, l.answer, "回答"), t.setStep(l.answer, "done", e.text.trim());
158
+ return;
159
+ }
160
+ e.type === "error" && t.setError(e.message);
161
+ return;
334
162
  }
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));
163
+ o.type === "turn.failed" && t.setError(o.error.message);
164
+ }
354
165
  }
355
- async function kt(t) {
166
+ async function ot(t) {
356
167
  await Promise.allSettled([
357
- A(),
358
- K(t)
168
+ v().initialize(t),
169
+ L(t)
359
170
  ]);
360
171
  }
361
- async function pt(t, e, o) {
362
- const s = L(), n = j(), a = J(), i = await A();
172
+ async function J(t, o, s) {
173
+ const e = g(), n = P(), r = N(), a = await M();
363
174
  return {
364
- hostManifest: i,
175
+ hostManifest: a,
365
176
  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?.() ?? {},
177
+ projectId: _(),
178
+ input: t,
179
+ memorySubjectId: T().getMemorySubjectId?.() ?? void 0,
180
+ memoryRefreshRequested: s?.forceMemoryRefresh === !0,
181
+ uiContext: T().getUiContext?.() ?? {},
372
182
  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,
383
- memoryEnabled: a.enabled,
384
- memoryReadEnabled: a.enabled,
183
+ sessionId: e.sessionId,
184
+ activeTaskId: e.activeTaskId,
185
+ activeTopic: e.activeTopic,
186
+ pendingTask: e.pendingTask,
187
+ conversationSummary: e.conversationSummary,
188
+ summarizedTurnCount: e.summarizedTurnCount,
189
+ conversationHistory: e.conversationHistory,
190
+ lastAssistantReply: e.getLastAssistantContent(),
191
+ invokedSkills: e.invokedSkills,
192
+ skillPermissionGrants: e.skillPermissionGrants,
193
+ memoryEnabled: r.enabled,
194
+ memoryReadEnabled: r.enabled,
385
195
  memoryWriteEnabled: !0
386
196
  },
387
197
  runtimeState: {
@@ -391,119 +201,79 @@ async function pt(t, e, o) {
391
201
  resumableAction: n.resumableAction,
392
202
  lastResolvedTarget: n.lastResolvedTarget
393
203
  },
394
- clientToolsManifestVersion: i.manifestDigest,
395
- clientToolManifest: i,
396
- skills: F(G()),
397
- frontendBuildId: i.frontendBuildId,
398
- manifestDigest: i.manifestDigest
204
+ clientToolsManifestVersion: a.manifestDigest,
205
+ clientToolManifest: a,
206
+ skills: C(E()),
207
+ frontendBuildId: a.frontendBuildId,
208
+ manifestDigest: a.manifestDigest
399
209
  }
400
210
  };
401
211
  }
402
- async function Pt(t, e, o) {
403
- const s = T(), n = e.getSignal(), { payload: a, hostManifest: i } = await pt(
212
+ async function nt(t, o, s) {
213
+ const e = o.getSignal(), { payload: n, hostManifest: r } = await J(
404
214
  t,
405
- n,
406
- o
407
- ), f = new Set(i.tools.map((m) => m.name)), p = {
215
+ e,
216
+ s
217
+ ), a = new Set(r.tools.map((i) => i.name)), u = {
408
218
  sideEffectByName: new Map(
409
- i.tools.map((m) => [m.name, m.sideEffect])
219
+ r.tools.map((i) => [i.name, i.sideEffect])
410
220
  )
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(
221
+ }, m = v(), I = g(), w = await m.startThread(I.sessionId, e), y = await m.startTurn(w.id, n, e);
222
+ e && (k.set(e, y.id), e.addEventListener(
425
223
  "abort",
426
224
  () => {
427
- q(h);
225
+ m.cancelTurn(y.id);
428
226
  },
429
227
  { once: !0 }
430
228
  ));
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();
229
+ for await (const i of m.streamTurn(y.id, e)) {
230
+ if (await z(o, i, u), (i.type === "item.started" || i.type === "item.updated") && i.item.type === "tool_call" && i.item.status === "waiting_for_client" && i.item.clientRequest) {
231
+ const d = {
232
+ id: i.item.id,
233
+ name: i.item.tool,
234
+ input: i.item.arguments,
235
+ displayName: i.item.displayName
236
+ }, c = await A(d, o, {
237
+ allowedHostNames: a
238
+ });
239
+ q(o, d, c, u), await m.submitToolResult(y.id, {
240
+ correlationId: i.item.clientRequest.correlationId,
241
+ success: c.success,
242
+ output: c.data,
243
+ error: c.error,
244
+ errorCode: c.errorCode,
245
+ trace: c.trace,
246
+ uiContext: T().getUiContext?.() ?? void 0
247
+ }, e);
248
+ continue;
249
+ }
250
+ if (await j(), i.type === "turn.failed")
251
+ throw new Error(i.error.message);
252
+ if (i.type === "turn.completed") {
253
+ const d = i.metadata ?? {}, c = d.sessionPatch;
254
+ return c && I.applySessionPatch(c), {
255
+ command: null,
256
+ memoryReplay: d.memoryReplay ?? null,
257
+ memoryDecision: d.memoryDecision ?? null,
258
+ assistantReply: i.finalResponse
259
+ };
476
260
  }
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
261
  }
262
+ return { command: null };
482
263
  }
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
- );
264
+ async function $(t) {
265
+ await v().cancelTurn(t);
494
266
  }
495
- function xt(t) {
267
+ function st(t) {
496
268
  if (!t) return;
497
- const e = N.get(t);
498
- e && (N.delete(t), q(e));
269
+ const o = k.get(t);
270
+ o && (k.delete(t), $(o));
499
271
  }
500
272
  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
273
+ z as applyLifecycleEvent,
274
+ $ as cancelRemoteSpotlightRun,
275
+ st as cancelRemoteSpotlightRunForSignal,
276
+ nt as runRemoteSpotlightPipeline,
277
+ q as settleHostToolCall,
278
+ ot as warmupSpotlightRemoteContext
509
279
  };