dsh-cheso-design 0.1.2 → 0.1.3

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/lib/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // src/index.ts
2
+ import { randomUUID as randomUUID2 } from "node:crypto";
2
3
  import path2 from "node:path";
3
4
  import { defineTool } from "@deepseek-ai/dsh-tools";
4
5
  import z from "@deepseek-ai/schemastery";
@@ -368,12 +369,21 @@ var ChesoApiError = class extends Error {
368
369
  this.retryAfter = retryAfter;
369
370
  }
370
371
  };
372
+ var FixedTokenRejected = class extends Error {
373
+ code = "fixed_token_rejected";
374
+ constructor() {
375
+ super("Cheso \u62D2\u7EDD\u4E86\u914D\u7F6E\u7684 API token\u3002\u8BF7\u66F4\u65B0\u6216\u79FB\u9664 DSH \u914D\u7F6E\u4E2D\u7684 token \u6216\u542F\u52A8\u73AF\u5883\u4E2D\u7684 CHESO_API_TOKEN\uFF0C\u7136\u540E\u91CD\u542F DSH\u3002");
376
+ }
377
+ };
371
378
  var ChesoApi = class {
372
379
  constructor(base, auth, fixedToken) {
373
380
  this.base = base;
374
381
  this.auth = auth;
375
382
  this.fixedToken = fixedToken;
376
383
  }
384
+ get usesFixedToken() {
385
+ return Boolean(this.fixedToken());
386
+ }
377
387
  /** 退出当前站点的 OAuth 登录。配置了固定 API 令牌时,提示用户从配置移除。 */
378
388
  async logout(signal) {
379
389
  if (this.fixedToken()) {
@@ -405,8 +415,17 @@ var ChesoApi = class {
405
415
  token = await this.auth.token(requestSignal, token);
406
416
  response = await send();
407
417
  }
408
- const payload = await response.json().catch(() => null);
409
- if (response.status === 401) throw new LoginRequired();
418
+ if (response.status === 401) {
419
+ await response.body?.cancel().catch(() => {
420
+ });
421
+ if (fixed) throw new FixedTokenRejected();
422
+ throw new LoginRequired();
423
+ }
424
+ const payload = await response.json().catch((error) => {
425
+ requestSignal.throwIfAborted();
426
+ if (!(error instanceof SyntaxError)) throw error;
427
+ return null;
428
+ });
410
429
  if (!response.ok || typeof payload?.code === "number" && payload.code !== 0) {
411
430
  const retryAfter = Number(response.headers.get("retry-after"));
412
431
  throw new ChesoApiError(response.status, payload?.code, retryAfter > 0 ? retryAfter : void 0);
@@ -414,6 +433,9 @@ var ChesoApi = class {
414
433
  if (!payload || typeof payload !== "object") throw new ChesoApiError(response.status);
415
434
  return payload.data ?? payload;
416
435
  }
436
+ whoami(signal) {
437
+ return this.request("/api/v1/whoami", { signal });
438
+ }
417
439
  /** 读取指定版本的文件详情。省略版本时,读取最新版本。 */
418
440
  file(fileId, { version, signal, devSet } = {}) {
419
441
  return this.request(`/api/v1/files/${chesoId(fileId)}${version ? `?version=${version}` : ""}`, { signal, devSet });
@@ -480,10 +502,11 @@ function isEmbedFormat(format) {
480
502
  }
481
503
 
482
504
  // src/files.ts
483
- import { openAsBlob, promises as fs } from "node:fs";
505
+ import { constants, createWriteStream, openAsBlob, promises as fs } from "node:fs";
484
506
  import { createHash as createHash2, randomUUID } from "node:crypto";
507
+ import { tmpdir } from "node:os";
485
508
  import path from "node:path";
486
- import { Readable } from "node:stream";
509
+ import { pipeline } from "node:stream/promises";
487
510
  var MIME_TYPES = {
488
511
  ".png": "image/png",
489
512
  ".jpg": "image/jpeg",
@@ -518,16 +541,130 @@ function transferSignal(signal) {
518
541
  const timeout = AbortSignal.timeout(12e4);
519
542
  return signal ? AbortSignal.any([signal, timeout]) : timeout;
520
543
  }
521
- async function uploadAttachment(api, filename, projectId, signal) {
522
- const name2 = safeFilename(filename);
523
- const stat = await fs.stat(filename).catch(() => void 0);
524
- if (!stat?.isFile()) throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u9644\u4EF6 ${name2}\uFF0C\u8BF7\u9009\u62E9\u666E\u901A\u6587\u4EF6\u3002`);
525
- const mime = MIME_TYPES[path.extname(name2).toLowerCase()] ?? "application/octet-stream";
526
- const file = await openAsBlob(filename, { type: mime });
527
- const hash = createHash2("md5");
528
- const source = Readable.fromWeb(file.stream(), { signal });
529
- for await (const chunk of source) hash.update(chunk);
530
- const body = { name: name2, size: file.size, hash: hash.digest("hex"), mime_type: mime, category: "attachment" };
544
+ function userAttachmentBlocks(agent) {
545
+ return (agent?.session?.deriveMessages?.() ?? []).reverse().find((message) => message.role === "user" && message.source.kind === "user")?.content.filter((block) => block.type === "file" || block.type === "image") ?? [];
546
+ }
547
+ async function authorizedSources(ctx, paths, site, exec, attachmentBlocks) {
548
+ const { agent, signal } = exec;
549
+ const store = ctx.get("attachments");
550
+ const attached = attachmentBlocks.flatMap((block) => {
551
+ if (!store || block.type !== "file" && block.type !== "image" || !("attachment" in block)) return [];
552
+ const ref = block.attachment;
553
+ const filename = block.type === "file" ? store.fileHostPath?.(ref) : store.imageHostPath?.(ref);
554
+ if (typeof filename !== "string" || !path.isAbsolute(filename)) return [];
555
+ const visiblePath = ctx.get("fs")?.processPathFromHostPath?.(filename);
556
+ const mime = block.type === "image" ? block.attachment.mediaType : void 0;
557
+ const name2 = ref.name ?? `image.${mime?.split("/")[1] ?? "png"}`;
558
+ return [{ filename, name: name2, mime, digest: String(ref.attachmentId), visiblePath }];
559
+ });
560
+ const approval = ctx.get("approval");
561
+ let cwd;
562
+ const needsApproval = /* @__PURE__ */ new Set();
563
+ const sources = [];
564
+ for (const requested of paths) {
565
+ signal.throwIfAborted();
566
+ const matches = attached.filter((file) => requested === file.digest || requested === file.filename || requested === file.visiblePath);
567
+ const candidates = matches.length ? matches : attached.filter((file) => requested === file.name);
568
+ const selected = new Map(candidates.map((file) => [file.digest, file]));
569
+ if (selected.size > 1) throw new Error("\u6709\u591A\u4E2A\u540C\u540D\u9644\u4EF6\uFF0C\u8BF7\u901A\u8FC7 DSH \u63D0\u4F9B\u7684\u9644\u4EF6\u8DEF\u5F84\u6307\u5B9A\u6587\u4EF6\u3002");
570
+ const attachment = selected.values().next().value;
571
+ if (attachment) {
572
+ sources.push(attachment);
573
+ continue;
574
+ }
575
+ if (!agent || !approval) throw new Error("\u5F53\u524D DSH \u65E0\u6CD5\u786E\u8BA4\u672C\u5730\u6587\u4EF6\u4E0A\u4F20\uFF0C\u8BF7\u5C06\u6587\u4EF6\u76F4\u63A5\u9644\u52A0\u5230\u6D88\u606F\u4E2D\u3002");
576
+ const workingDirectory = cwd ??= await ctx.workingDirectory.ensure(agent, signal);
577
+ const requestedPath = path.resolve(workingDirectory, requested);
578
+ const filename = await canonicalPath(requestedPath);
579
+ const beforeApproval = await fs.stat(filename, { bigint: true }).catch(() => void 0);
580
+ if (!beforeApproval?.isFile()) throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u9644\u4EF6 ${safeFilename(requestedPath)}\uFF0C\u8BF7\u9009\u62E9\u666E\u901A\u6587\u4EF6\u3002`);
581
+ needsApproval.add(filename);
582
+ sources.push({ filename, name: path.basename(requestedPath), beforeApproval });
583
+ }
584
+ if (needsApproval.size) {
585
+ const files = [...needsApproval].map((file) => JSON.stringify(file)).join(", ");
586
+ const outcome = await approval.request({
587
+ agent,
588
+ toolName: exec.name,
589
+ callId: exec.callId,
590
+ signal,
591
+ reason: `\u5141\u8BB8\u5C06\u8FD9\u4E9B\u672C\u5730\u6587\u4EF6\u4E0A\u4F20\u5230 ${site} \u5417\uFF1F
592
+ ${files}`,
593
+ displayReason: { en: `Upload these local files to ${site}?
594
+ ${files}`, zh: `\u5141\u8BB8\u5C06\u8FD9\u4E9B\u672C\u5730\u6587\u4EF6\u4E0A\u4F20\u5230 ${site} \u5417\uFF1F
595
+ ${files}` }
596
+ });
597
+ signal.throwIfAborted();
598
+ if (outcome !== "allowed-once") throw new Error("\u672C\u5730\u6587\u4EF6\u4E0A\u4F20\u672A\u83B7\u6388\u6743\u3002");
599
+ }
600
+ return sources;
601
+ }
602
+ function sameFileRevision(first, second) {
603
+ return first.dev === second.dev && first.ino === second.ino && first.size === second.size && first.mtimeNs === second.mtimeNs && first.ctimeNs === second.ctimeNs;
604
+ }
605
+ async function canonicalPath(filename) {
606
+ return fs.realpath(filename).catch(() => {
607
+ throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u9644\u4EF6 ${safeFilename(filename)}\u3002`);
608
+ });
609
+ }
610
+ async function prepareAttachment(source, snapshot, signal) {
611
+ const { filename } = source;
612
+ const name2 = safeFilename(source.name);
613
+ const mime = source.mime ?? MIME_TYPES[path.extname(name2).toLowerCase()] ?? "application/octet-stream";
614
+ const canonical = source.digest ? await canonicalPath(filename) : filename;
615
+ const handle = await fs.open(canonical, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(() => {
616
+ throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u9644\u4EF6 ${name2}\uFF0C\u8BF7\u9009\u62E9\u666E\u901A\u6587\u4EF6\u3002`);
617
+ });
618
+ try {
619
+ const before = await handle.stat({ bigint: true });
620
+ const actual = await fs.stat(canonical, { bigint: true });
621
+ if (!before.isFile() || before.dev !== actual.dev || before.ino !== actual.ino || await canonicalPath(canonical) !== canonical) {
622
+ throw new Error(`\u9644\u4EF6 ${name2} \u7684\u8DEF\u5F84\u5DF2\u53D8\u5316\uFF0C\u6216\u76EE\u6807\u4E0D\u662F\u666E\u901A\u6587\u4EF6\u3002`);
623
+ }
624
+ if (source.beforeApproval && !sameFileRevision(source.beforeApproval, before)) {
625
+ throw new Error(`\u9644\u4EF6 ${name2} \u5728\u7B49\u5F85\u5BA1\u6279\u671F\u95F4\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u6587\u4EF6\u3002`);
626
+ }
627
+ const hash = createHash2("md5");
628
+ const digest = source.digest ? createHash2("sha256") : void 0;
629
+ await pipeline(
630
+ handle.createReadStream({ autoClose: false }),
631
+ async function* (chunks) {
632
+ for await (const chunk of chunks) {
633
+ hash.update(chunk);
634
+ digest?.update(chunk);
635
+ yield chunk;
636
+ }
637
+ },
638
+ createWriteStream(snapshot, { flags: "wx", mode: 384 }),
639
+ { signal }
640
+ );
641
+ const after = await handle.stat({ bigint: true });
642
+ if (!sameFileRevision(before, after) || digest && `sha256:${digest.digest("hex")}` !== source.digest) {
643
+ throw new Error(`\u9644\u4EF6 ${name2} \u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u6587\u4EF6\u3002`);
644
+ }
645
+ return { file: await openAsBlob(snapshot, { type: mime }), name: name2, mime, hash: hash.digest("hex") };
646
+ } finally {
647
+ await handle.close();
648
+ }
649
+ }
650
+ async function uploadAttachments(ctx, api, paths, projectId, exec, attachmentBlocks) {
651
+ const sources = await authorizedSources(ctx, paths, api.base, exec, attachmentBlocks);
652
+ const directory = await fs.mkdtemp(path.join(tmpdir(), "dsh-cheso-upload-"));
653
+ try {
654
+ const prepared = [];
655
+ for (const [index, source] of sources.entries()) {
656
+ prepared.push(await prepareAttachment(source, path.join(directory, String(index)), exec.signal));
657
+ }
658
+ const ids = [];
659
+ for (const file of prepared) ids.push(await uploadAttachment(api, file, projectId, exec.signal));
660
+ return ids;
661
+ } finally {
662
+ await fs.rm(directory, { recursive: true, force: true });
663
+ }
664
+ }
665
+ async function uploadAttachment(api, attachment, projectId, signal) {
666
+ const { name: name2, mime, file, hash } = attachment;
667
+ const body = { name: name2, size: file.size, hash, mime_type: mime, category: "attachment" };
531
668
  const presign = (attachmentName) => api.request("/api/v1/files/presign", {
532
669
  body: { ...body, ...projectId ? { project_id: projectId, create_only: true, file_path: `attachments/${attachmentName}` } : {} },
533
670
  signal
@@ -560,14 +697,20 @@ async function uploadAttachment(api, filename, projectId, signal) {
560
697
  // src/tasks.ts
561
698
  import { setTimeout as sleep2 } from "node:timers/promises";
562
699
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "terminated", "rolled_back"]);
563
- async function resultFor(api, taskId, signal) {
700
+ async function resultFor(api, taskId, signal, onHandoff) {
564
701
  const visited = /* @__PURE__ */ new Set();
565
702
  let id = taskId;
703
+ let activeId;
566
704
  while (!visited.has(id) && visited.size < 30) {
567
705
  visited.add(id);
568
706
  const result = await api.request(`/api/v1/plans/${chesoId(id)}/result`, { signal });
569
- if (!result.next_plan_id) return { id, result };
570
- id = result.next_plan_id;
707
+ if (result.reason === "hard_stopped" || result.status === "hard_stopped") {
708
+ return { id, result: { ...result, status: "terminated", reason: void 0 }, activeId: void 0 };
709
+ }
710
+ if (!TERMINAL.has(result.status) && result.status !== "pending") activeId = id;
711
+ if (!result.next_plan_id) return { id, result, activeId };
712
+ id = chesoId(result.next_plan_id);
713
+ if (!visited.has(id)) onHandoff?.(id, activeId);
571
714
  }
572
715
  throw new Error("Cheso \u4EFB\u52A1\u63A5\u7EED\u94FE\u5F02\u5E38\u3002");
573
716
  }
@@ -600,7 +743,60 @@ function questionPreviews(interaction) {
600
743
  function transientPollError(error) {
601
744
  return error instanceof TypeError || error instanceof DOMException && error.name === "TimeoutError" || error instanceof ChesoApiError && (error.status === 429 || error.status >= 500);
602
745
  }
603
- async function waitForTask(api, taskId, timeoutSec, knownProject, signal, repliedQuestion) {
746
+ async function stopTask(api, taskId, previousTaskId, signal) {
747
+ const stoppedResult = (id2, result2) => ({
748
+ task_id: id2,
749
+ status: result2.status,
750
+ ...result2.status === "terminated" ? { files: filesOf(result2) } : {}
751
+ });
752
+ const stopTarget = async (chain) => {
753
+ if (chain.result.status !== "pending") return chain.id;
754
+ if (chain.activeId) return chain.activeId;
755
+ if (!previousTaskId || previousTaskId === chain.id) return chain.id;
756
+ const previous = await resultFor(api, previousTaskId, signal);
757
+ return previous.activeId ?? chain.id;
758
+ };
759
+ const { id, result, activeId } = await resultFor(api, taskId, signal);
760
+ if (TERMINAL.has(result.status)) return stoppedResult(id, result);
761
+ const stopId = await stopTarget({ id, result, activeId });
762
+ try {
763
+ await api.request(`/api/v1/plans/${chesoId(stopId)}/terminate`, { body: {}, signal });
764
+ } catch (error) {
765
+ if (!(error instanceof ChesoApiError && error.code === 1101)) throw error;
766
+ const latest = await resultFor(api, taskId, signal);
767
+ if (TERMINAL.has(latest.result.status)) return stoppedResult(latest.id, latest.result);
768
+ const nextStopId = await stopTarget(latest);
769
+ if (nextStopId === stopId) {
770
+ if (latest.result.status === "pending") return stoppedResult(latest.id, latest.result);
771
+ throw error;
772
+ }
773
+ try {
774
+ await api.request(`/api/v1/plans/${chesoId(nextStopId)}/terminate`, { body: {}, signal });
775
+ } catch (retryError) {
776
+ if (!(retryError instanceof ChesoApiError && retryError.code === 1101)) throw retryError;
777
+ const settled = await resultFor(api, taskId, signal);
778
+ if (TERMINAL.has(settled.result.status) || settled.result.status === "pending") return stoppedResult(settled.id, settled.result);
779
+ throw retryError;
780
+ }
781
+ }
782
+ const deadline = AbortSignal.timeout(1e4);
783
+ const pollSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
784
+ try {
785
+ while (!pollSignal.aborted) {
786
+ const latest = await resultFor(api, id, pollSignal).catch((error) => {
787
+ if (!transientPollError(error)) throw error;
788
+ });
789
+ if (latest && TERMINAL.has(latest.result.status)) return stoppedResult(latest.id, latest.result);
790
+ await sleep2(1e3, void 0, { signal: pollSignal });
791
+ }
792
+ } catch (error) {
793
+ signal?.throwIfAborted();
794
+ if (!deadline.aborted && !(error instanceof ChesoApiError || error instanceof LoginRequired)) throw error;
795
+ }
796
+ signal?.throwIfAborted();
797
+ return { task_id: id, status: "stopping" };
798
+ }
799
+ async function waitForTask(api, taskId, timeoutSec, knownProject, signal, repliedQuestion, onHandoff) {
604
800
  const timeout = AbortSignal.timeout(Math.floor(timeoutSec * 1e3));
605
801
  const waitSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
606
802
  let latest;
@@ -611,7 +807,10 @@ async function waitForTask(api, taskId, timeoutSec, knownProject, signal, replie
611
807
  while (!waitSignal.aborted) {
612
808
  let delay = 3e3;
613
809
  try {
614
- latest = await resultFor(api, current, waitSignal);
810
+ latest = await resultFor(api, current, waitSignal, (id, activeId) => {
811
+ current = id;
812
+ onHandoff?.(id, activeId);
813
+ });
615
814
  current = latest.id;
616
815
  failures = 0;
617
816
  waitingForUser = latest.result.status === "interact" && interactionKey(current, latest.result.interaction) !== repliedQuestion;
@@ -632,17 +831,24 @@ async function waitForTask(api, taskId, timeoutSec, knownProject, signal, replie
632
831
  return { task_id: current, project_id: knownProject, status: "running", done: false, repliedQuestion };
633
832
  }
634
833
  const { result } = latest;
834
+ if (result.status === "terminated") {
835
+ return {
836
+ task_id: current,
837
+ status: result.status,
838
+ project_id: knownProject,
839
+ done: true,
840
+ files: filesOf(result),
841
+ message: result.reason,
842
+ answer: result.result?.text
843
+ };
844
+ }
635
845
  const projectId = knownProject ?? (await api.request(`/api/v1/plans/${chesoId(current)}`, { signal }).catch((error) => {
636
846
  signal?.throwIfAborted();
637
847
  if (error instanceof LoginRequired) throw error;
638
848
  return { project_id: void 0 };
639
849
  })).project_id;
640
- let files = filesOf(result);
641
850
  const questions = waitingForUser ? questionsOf(result.interaction) : [];
642
851
  const message = waitingForUser ? questions.map(({ question, options }, index) => `${index + 1}. ${question}${options?.length ? `\uFF08${options.map((option) => option.label).join(" / ")}\uFF09` : ""}`).join("\n") : result.reason;
643
- if (!result.result?.files?.length && projectId && result.status === "completed") {
644
- files = (await api.projectFiles(projectId, signal)).filter((file) => file.category === "result");
645
- }
646
852
  return {
647
853
  task_id: current,
648
854
  status: result.status,
@@ -650,12 +856,15 @@ async function waitForTask(api, taskId, timeoutSec, knownProject, signal, replie
650
856
  project_id: projectId,
651
857
  answer: result.result?.text,
652
858
  message,
653
- files,
859
+ files: filesOf(result),
654
860
  ...waitingForUser ? {
655
861
  interaction: { key: interactionKey(current, result.interaction), questions, previews: questionPreviews(result.interaction) }
656
862
  } : {}
657
863
  };
658
864
  }
865
+ function hasDuplicateQuestions(questions) {
866
+ return new Set(questions.map((question) => question.question)).size !== questions.length;
867
+ }
659
868
  function userQuestionsFor(questions) {
660
869
  return questions.map(({ multi_select, ...question }, index) => ({
661
870
  ...question,
@@ -693,8 +902,9 @@ async function askWhileQuestionIsOpen(api, taskId, question, ask, signal) {
693
902
  stop.abort();
694
903
  }
695
904
  }
696
- async function replyToTask(api, taskId, question, reply, signal) {
905
+ async function replyToTask(api, taskId, question, reply, signal, submissionSignal = signal) {
697
906
  signal?.throwIfAborted();
907
+ if (hasDuplicateQuestions(question.questions)) throw new Error("\u8FD9\u6279\u63D0\u95EE\u5305\u542B\u91CD\u590D\u9898\u5E72\uFF0C\u8BF7\u5728 Cheso \u9879\u76EE\u4E2D\u56DE\u7B54\u3002");
698
908
  const questions = userQuestionsFor(question.questions);
699
909
  const answers = new Map(reply.answers.map((answer) => [answer.id, answer]));
700
910
  if (!questions.length || answers.size !== questions.length || reply.answers.length !== questions.length) {
@@ -712,6 +922,7 @@ async function replyToTask(api, taskId, question, reply, signal) {
712
922
  const { id, result } = await resultFor(api, taskId, signal);
713
923
  if (result.status !== "interact" || interactionKey(id, result.interaction) !== question.key) return "changed";
714
924
  const skip = pairs.length === 0;
925
+ signal?.throwIfAborted();
715
926
  try {
716
927
  await api.request(`/api/v1/plans/${chesoId(id)}/interact`, {
717
928
  body: {
@@ -721,13 +932,17 @@ async function replyToTask(api, taskId, question, reply, signal) {
721
932
  },
722
933
  skip
723
934
  },
724
- signal
935
+ signal: submissionSignal
725
936
  });
726
937
  } catch (error) {
727
938
  if (!(error instanceof ChesoApiError && error.code === 1101)) throw error;
728
939
  return "expired";
729
940
  }
730
- return { answers: reviewed.map(({ label, values }) => ({ label, values })) };
941
+ return { answers: reviewed.map(({ label, question: question2, values }) => ({
942
+ label,
943
+ ...question2 === label ? {} : { question: question2 },
944
+ values
945
+ })) };
731
946
  }
732
947
 
733
948
  // src/sites.ts
@@ -735,6 +950,10 @@ var CHESO_SITES = {
735
950
  global: "https://cheso.ai"
736
951
  };
737
952
  var CHESO_SITE_OPTIONS = ["configured", "global"];
953
+ function projectSite(projectUrl) {
954
+ if (typeof projectUrl !== "string") return void 0;
955
+ return projectUrl.match(/^(.*)\/agent\/[A-Za-z0-9_-]+\/?$/)?.[1];
956
+ }
738
957
 
739
958
  // src/index.ts
740
959
  var name = "cheso";
@@ -753,6 +972,8 @@ var Config = z.object({
753
972
  /** 可选的 API 令牌。留空时使用 DSH 保存的登录授权。 */
754
973
  token: z.string().default("")
755
974
  });
975
+ var STOP_SUMMARY = "Cheso \u4EFB\u52A1\u5DF2\u505C\u6B62\u3002\u8BF7\u7528\u4E00\u4E24\u53E5\u8BDD\u544A\u77E5\u7528\u6237\uFF0C\u6309\u9700\u63D0\u53CA\u4EFB\u52A1\u7ED3\u679C\u5217\u51FA\u7684\u6210\u54C1\u548C\u9879\u76EE\u94FE\u63A5\u3002\u4E0D\u8981\u518D\u67E5\u8BE2\u9879\u76EE\u6587\u4EF6\u3001\u7EE7\u7EED\u7B49\u5F85\u6216\u91CD\u65B0\u63D0\u4EA4\u4EFB\u52A1\u3002";
976
+ var DSH_LOGIN_REQUIRED = "Cheso \u672A\u767B\u5F55\u3002\u8BF7\u7528\u6237\u4ECE DSH \u767B\u5F55\u5361\u83B7\u53D6\u6388\u6743\u94FE\u63A5\u5E76\u5B8C\u6210\u6D4F\u89C8\u5668\u6388\u6743\uFF0C\u7136\u540E\u518D\u7EE7\u7EED\u3002";
756
977
  function includesStartupEntry(entries, id) {
757
978
  return entries.some((entry) => entry.id === id || entry.group === true && Array.isArray(entry.config) && includesStartupEntry(entry.config, id));
758
979
  }
@@ -839,6 +1060,8 @@ var artifactCardSchema = {
839
1060
  },
840
1061
  embed_base_url: { type: "string" },
841
1062
  base_url: { type: "string" },
1063
+ retry_call_id: { type: "string" },
1064
+ previous_task_id: { type: "string" },
842
1065
  message: { type: "string" },
843
1066
  answer: { type: "string" }
844
1067
  }
@@ -861,6 +1084,7 @@ var waitCardSchema = {
861
1084
  additionalProperties: false,
862
1085
  properties: {
863
1086
  label: { type: "string", required: true },
1087
+ question: { type: "string" },
864
1088
  values: { type: "array", required: true, items: { type: "string" } }
865
1089
  }
866
1090
  }
@@ -880,9 +1104,33 @@ function cardPayload(view, config, extra = {}) {
880
1104
  answer: typeof view.answer === "string" ? view.answer.slice(0, 1200) : void 0,
881
1105
  artifacts: artifactsOf(view),
882
1106
  embed_base_url: trimBaseUrl(config.embedBaseUrl),
1107
+ base_url: config.baseUrl,
1108
+ previous_task_id: typeof view.previous_task_id === "string" ? view.previous_task_id : void 0,
883
1109
  ...extra
884
1110
  });
885
1111
  }
1112
+ async function stoppedCard(result, config, signal, extra) {
1113
+ let projectId;
1114
+ try {
1115
+ let id = result.project_id;
1116
+ if (!id) {
1117
+ const deadline = AbortSignal.timeout(5e3);
1118
+ const plan = await config.api.request(`/api/v1/plans/${chesoId(result.task_id)}`, {
1119
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline
1120
+ });
1121
+ id = plan.project_id;
1122
+ }
1123
+ if (id) projectId = chesoId(id);
1124
+ } catch {
1125
+ signal?.throwIfAborted();
1126
+ }
1127
+ return cardPayload({
1128
+ ...result,
1129
+ status: "terminated",
1130
+ project_id: projectId,
1131
+ project_url: projectId ? config.api.projectUrl(projectId) : void 0
1132
+ }, config, extra);
1133
+ }
886
1134
  function projectIdFromReference(reference, baseUrl) {
887
1135
  const input = reference.trim();
888
1136
  if (/^project_[a-z0-9]+$/i.test(input)) return input;
@@ -914,6 +1162,45 @@ function renderCard(payload, headline) {
914
1162
  lines.push(`[cheso-card]${JSON.stringify(payload)}`);
915
1163
  return [{ type: "text", text: lines.join("\n") }];
916
1164
  }
1165
+ function* historicalCards(agent) {
1166
+ const messages = agent?.session?.deriveMessages?.() ?? [];
1167
+ const names = /* @__PURE__ */ new Set(["cheso_create", "cheso_wait", "cheso_stop", "cheso_login", "cheso_project_files"]);
1168
+ const calls = new Set(messages.flatMap((message) => message.role === "assistant" ? message.content.flatMap((block) => block.type === "tool-call" && names.has(block.name) ? [block.id] : []) : []));
1169
+ for (const message of messages.reverse()) {
1170
+ if (message.role !== "tool" || message.isError || !calls.has(message.source.callId)) continue;
1171
+ for (const block of message.content) {
1172
+ if (block.type !== "text") continue;
1173
+ const marker = "\n[cheso-card]";
1174
+ const start = block.text.lastIndexOf(marker);
1175
+ if (start < 0) continue;
1176
+ try {
1177
+ const card = JSON.parse(block.text.slice(start + marker.length));
1178
+ if (card && typeof card === "object" && !Array.isArray(card)) yield card;
1179
+ } catch {
1180
+ }
1181
+ }
1182
+ }
1183
+ }
1184
+ function historicalTask(taskId, agent) {
1185
+ const routes = /* @__PURE__ */ new Map();
1186
+ for (const card of historicalCards(agent)) {
1187
+ if (card.task_id !== taskId || card.status === "login_required") continue;
1188
+ const base = typeof card.base_url === "string" ? card.base_url : projectSite(card.project_url);
1189
+ if (!base) continue;
1190
+ const route = routes.get(base) ?? {};
1191
+ if (typeof card.project_id === "string") route.projectId ??= card.project_id;
1192
+ if (typeof card.previous_task_id === "string") route.previousTaskId ??= card.previous_task_id;
1193
+ routes.set(base, route);
1194
+ }
1195
+ return routes;
1196
+ }
1197
+ function historicalLoginSite(agent) {
1198
+ for (const { status, base_url } of historicalCards(agent)) {
1199
+ if ((status === "login_pending" || status === "login_required") && typeof base_url === "string" && base_url) {
1200
+ return base_url;
1201
+ }
1202
+ }
1203
+ }
917
1204
  function previewSite(configs, projectUrl, embedBaseUrl) {
918
1205
  if (projectUrl) {
919
1206
  const project = URL.canParse(projectUrl) ? new URL(projectUrl) : void 0;
@@ -948,7 +1235,45 @@ function apply(ctx, pluginConfig) {
948
1235
  };
949
1236
  const currentConfig = () => configs[pluginConfig.site.get()];
950
1237
  const previewConfigs = Object.values(configs);
1238
+ const configForSite = (baseUrl) => baseUrl === void 0 ? currentConfig() : previewConfigs.find((config) => config.baseUrl === baseUrl);
1239
+ const unknownSite = "\u8BE5\u7AD9\u70B9\u5DF2\u4E0D\u5728\u63D2\u4EF6\u914D\u7F6E\u4E2D\u3002\u8BF7\u68C0\u67E5\u7AD9\u70B9\u8BBE\u7F6E\u5E76\u91CD\u65B0\u53D1\u8D77\u8BF7\u6C42\u3002";
1240
+ const createRetries = /* @__PURE__ */ new WeakMap();
951
1241
  const pendingTasks = /* @__PURE__ */ new Map();
1242
+ const recentTaskRoutes = /* @__PURE__ */ new Map();
1243
+ const routingKey = (config, id) => JSON.stringify([config.baseUrl, id]);
1244
+ const rememberTask = (id, { config, projectId, agentType, previousTaskId }) => {
1245
+ const key = routingKey(config, id);
1246
+ recentTaskRoutes.delete(key);
1247
+ recentTaskRoutes.set(key, { config, projectId, agentType, previousTaskId });
1248
+ if (recentTaskRoutes.size > 1024) recentTaskRoutes.delete(recentTaskRoutes.keys().next().value);
1249
+ };
1250
+ const routeTask = (id, site, agent) => {
1251
+ chesoId(id);
1252
+ const history = historicalTask(id, agent);
1253
+ const cachedSites = /* @__PURE__ */ new Set();
1254
+ for (const config2 of previewConfigs) {
1255
+ const key2 = routingKey(config2, id);
1256
+ if (pendingTasks.has(key2) || recentTaskRoutes.has(key2)) cachedSites.add(config2.baseUrl);
1257
+ }
1258
+ const knownSites = history.size ? new Set(history.keys()) : cachedSites;
1259
+ if (site && knownSites.size && !knownSites.has(site) && !cachedSites.has(site)) {
1260
+ throw new Error("\u6307\u5B9A\u7684 Cheso \u7AD9\u70B9\u4E0E\u539F\u4EFB\u52A1\u4E0D\u4E00\u81F4\u3002");
1261
+ }
1262
+ if (!site && knownSites.size > 1) throw new Error("\u591A\u4E2A Cheso \u7AD9\u70B9\u5B58\u5728\u76F8\u540C\u4EFB\u52A1 ID\uFF0C\u8BF7\u4F20\u5165\u539F\u4EFB\u52A1\u7ED3\u679C\u4E2D\u7684 base_url\u3002");
1263
+ const base = site || knownSites.values().next().value;
1264
+ const selected = currentConfig();
1265
+ const config = !base || selected.baseUrl === base ? selected : previewConfigs.find((candidate) => candidate.baseUrl === base);
1266
+ if (!config) throw new Error("\u539F\u4EFB\u52A1\u7684 Cheso \u7AD9\u70B9\u5DF2\u4E0D\u5728\u63D2\u4EF6\u914D\u7F6E\u4E2D\uFF0C\u8BF7\u6062\u590D\u539F\u7AD9\u70B9\u914D\u7F6E\u540E\u91CD\u8BD5\u3002");
1267
+ const key = routingKey(config, id);
1268
+ const remembered = recentTaskRoutes.get(key);
1269
+ const saved = history.get(config.baseUrl);
1270
+ return pendingTasks.get(key) ?? {
1271
+ config: remembered?.config ?? config,
1272
+ projectId: remembered?.projectId ?? saved?.projectId,
1273
+ previousTaskId: remembered?.previousTaskId ?? saved?.previousTaskId,
1274
+ agentType: remembered?.agentType
1275
+ };
1276
+ };
952
1277
  const waitQuestionActivity = /* @__PURE__ */ new Map();
953
1278
  const receiptsByExecution = /* @__PURE__ */ new WeakMap();
954
1279
  ctx.on("tools/execute", async (exec, next) => {
@@ -966,6 +1291,10 @@ function apply(ctx, pluginConfig) {
966
1291
  };
967
1292
  }, { global: true });
968
1293
  const login = async (config, signal) => {
1294
+ if (config.api.usesFixedToken) {
1295
+ await config.api.whoami(signal);
1296
+ return { status: "signed_in", base_url: config.baseUrl };
1297
+ }
969
1298
  const webServer = ctx.get("webServer");
970
1299
  let root;
971
1300
  if (webServer) {
@@ -979,8 +1308,11 @@ function apply(ctx, pluginConfig) {
979
1308
  };
980
1309
  const checkLogin = async (config, signal) => {
981
1310
  try {
982
- const signedIn = await config.api.auth.wait(4e3, signal);
983
- return { status: signedIn ? "signed_in" : "waiting", base_url: config.baseUrl };
1311
+ if (!config.api.usesFixedToken && !await config.api.auth.wait(4e3, signal)) {
1312
+ return { status: "waiting", base_url: config.baseUrl };
1313
+ }
1314
+ await config.api.whoami(AbortSignal.any([signal, AbortSignal.timeout(5e3)]));
1315
+ return { status: "signed_in", base_url: config.baseUrl };
984
1316
  } catch (error) {
985
1317
  if (!(error instanceof LoginRequired)) throw error;
986
1318
  return { status: "login_required", base_url: config.baseUrl };
@@ -990,7 +1322,7 @@ function apply(ctx, pluginConfig) {
990
1322
  promptCtx.effect(() => promptCtx.systemPrompt.section({
991
1323
  name: "cheso:plugin-routing",
992
1324
  order: promptCtx.systemPrompt.getSectionOrder("TOOLS_SDK"),
993
- text: "For Cheso requests in DSH, use only the dsh-cheso-design cheso_* tools. If the plugin does not support an action, direct the user to Cheso. When creating or revising a deliverable in a named project, call cheso_create directly with project_id. Copy the user\u2019s original task wording into cheso_create.prompt verbatim, including their priorities. Include earlier user-provided or user-approved text only when the user explicitly refers to it. Do not rewrite, expand, or add an audience, language, style, outline, output format, or other requirements. Leave unspecified choices to Cheso. Use cheso_project_files with show_card: true when the user asks to see the project files or artifacts. Leave show_card unset when checking project files for your own context. After creation, use one cheso_wait call at a time and continue with the existing task if it is still running. Use cheso_wait to handle every Cheso question, including follow-ups and confirmations of a revised outline. The plugin shows the original questions and submits the user\u2019s answers or explicit skips directly. If Cheso closes the question itself, the plugin resumes waiting. Do not recreate Cheso questions with another tool, answer or skip on the user\u2019s behalf, or treat a previous answer as approval of a later question. If cheso_wait returns interact, end the turn and direct the user to the Cheso project to answer. Do not retry until the user says they have answered or skipped there. When cheso_wait returns artifacts, deliver the online result through its card and the Open in Cheso link. Do not query the same project again for delivery, download artifacts to the workspace, or look for local copies. Let DSH Host handle Cheso credentials. Do not read credential files or extract tokens. Only perform format conversion when the user explicitly asks to convert or export. A request to make a PPT alone does not authorize a separate export."
1325
+ text: "For Cheso requests in DSH, use only the native dsh-cheso-design cheso_* tools. The catalog entry named cheso is a separate CLI workflow: do not load it or run Cheso shell commands, even if that skill was loaded earlier. The two integrations have separate sign-ins. Start deliverable requests with cheso_create, without a login preflight. If a tool returns login_required, direct the user to its DSH login card. Use cheso_login for an explicit sign-in request, cheso_login_wait with the authorization card base_url after the user authorizes, and cheso_whoami when asked about the account. If the plugin does not support an action, direct the user to Cheso. After the user completes OAuth and asks to continue a blocked creation, call cheso_create with the retry_call_id from that creation result. It reuses the original request, attachments, and site; do not compose a new request. If a fixed API token was rejected, tell the user to update or remove it in their DSH configuration or startup environment. When creating or revising a deliverable in a named project, call cheso_create directly with project_id. Copy the user\u2019s original task wording into cheso_create.prompt verbatim, including their priorities. For files the user asks Cheso to use, pass the attachment names or exact paths in cheso_create.files. Include earlier user-provided or user-approved text only when the user explicitly refers to it. Do not rewrite, expand, or add an audience, language, style, outline, output format, or other requirements. Leave unspecified choices to Cheso. Use cheso_project_files with show_card: true when the user asks to see the project files or artifacts. Leave show_card unset when checking project files for your own context. After creation, use one cheso_wait call at a time and continue with the existing task if it is still running. When waiting, stopping, or following up on a task, pass the original result base_url as task_site when available. Treat terminated (including hard_stopped) as final. Briefly report the stop and any artifacts confirmed by the task result. Do not list project files, wait again, or resubmit the stopped task. If the user asks to stop a Cheso task, call cheso_stop with the task ID from this conversation. When cheso_wait yields to a stop request, handle it with cheso_stop and report the returned status. When cheso_wait yields to a new user message, address that message first. To pass a correction or extra instructions for the active Cheso task, call cheso_create with follow_up_task_id set to that task ID and prompt set to the user\u2019s exact message. Wait on the returned task ID. If no task ID is returned for the follow-up, tell the user the result and link to the Cheso project without resubmitting. Use cheso_wait to handle every Cheso question, including follow-ups and confirmations of a revised outline. The plugin shows the original questions and submits the user\u2019s answers or explicit skips directly. If Cheso closes the question itself, the plugin resumes waiting. Do not recreate Cheso questions with another tool, answer or skip on the user\u2019s behalf, or treat a previous answer as approval of a later question. If cheso_wait returns interact, end the turn and direct the user to the Cheso project to answer. Do not retry until the user says they have answered or skipped there. When cheso_wait returns completed with artifacts, deliver the online result through its card and the Open in Cheso link. Do not query the same project again for delivery, download artifacts to the workspace, or look for local copies. Let DSH Host handle Cheso credentials. Do not read credential files or extract tokens. Only perform format conversion when the user explicitly asks to convert or export. A request to make a PPT alone does not authorize a separate export."
994
1326
  }), "cheso: plugin routing");
995
1327
  });
996
1328
  ctx.inject(["webServer"], (webCtx) => {
@@ -1034,70 +1366,131 @@ function apply(ctx, pluginConfig) {
1034
1366
  ctx.tools.register(
1035
1367
  defineTool({
1036
1368
  name: "cheso_create",
1037
- description: "\u7528 dsh-cheso-design \u521B\u5EFA\u6216\u4FEE\u6539\u6210\u54C1\uFF1APPT/\u6F14\u793A\u6587\u7A3F\u3001\u6D77\u62A5/\u56FE\u7247\u3001\u52A8\u6548\u89C6\u9891\u3001\u7F51\u9875\u3001\u62A5\u544A\u7B49\u3002\u7528\u6237\u6307\u5B9A\u5DF2\u6709\u9879\u76EE\u7EE7\u7EED\u505A\u65F6\uFF0C\u5C06\u9879\u76EE ID \u6216\u5B8C\u6574\u94FE\u63A5\u586B\u5165 project_id\uFF0C\u76F4\u63A5\u8C03\u7528\u6B64\u5DE5\u5177\u3002\u53EA\u6709\u7528\u6237\u8981\u6C42\u67E5\u770B\u9879\u76EE\u6587\u4EF6\u6216\u4EFB\u52A1\u786E\u5B9E\u9700\u8981\u9009\u53D6\u67D0\u4E2A\u6587\u4EF6\u65F6\uFF0C\u624D\u8C03\u7528 cheso_project_files\u3002\u521B\u5EFA\u6210\u529F\u540E\u7528\u8FD4\u56DE\u7684 task_id \u8C03\u7528\u4E00\u6B21 cheso_wait \u7B49\u5F85\u7ED3\u679C\u3002\u4EFB\u52A1\u6309\u7528\u6237\u7684 Cheso \u8D26\u53F7\u4E0E\u79EF\u5206\u6267\u884C\u3002",
1369
+ description: "\u7528 dsh-cheso-design \u521B\u5EFA\u6216\u4FEE\u6539\u6210\u54C1\uFF1APPT/\u6F14\u793A\u6587\u7A3F\u3001\u6D77\u62A5/\u56FE\u7247\u3001\u52A8\u6548\u89C6\u9891\u3001\u7F51\u9875\u3001\u62A5\u544A\u7B49\u3002\u76F4\u63A5\u8C03\u7528\u672C\u5DE5\u5177\u5F00\u59CB\u4EFB\u52A1\uFF0C\u7531 DSH \u68C0\u67E5\u6388\u6743\uFF1B\u4E0D\u9700\u8981\u5148\u68C0\u67E5\u767B\u5F55\u3002\u7528\u6237\u6307\u5B9A\u5DF2\u6709\u9879\u76EE\u7EE7\u7EED\u505A\u65F6\uFF0C\u5C06\u9879\u76EE ID \u6216\u5B8C\u6574\u94FE\u63A5\u586B\u5165 project_id\uFF0C\u76F4\u63A5\u8C03\u7528\u6B64\u5DE5\u5177\u3002\u7528\u6237\u66F4\u6B63\u6216\u8865\u5145\u5F53\u524D Cheso \u4EFB\u52A1\u7684\u9700\u6C42\u65F6\uFF0C\u4F20\u5165 follow_up_task_id\uFF0C\u628A\u6D88\u606F\u53D1\u5230\u8BE5\u4EFB\u52A1\u7684 Cheso \u5BF9\u8BDD\u3002\u53EA\u6709\u7528\u6237\u8981\u6C42\u67E5\u770B\u9879\u76EE\u6587\u4EF6\u6216\u4EFB\u52A1\u786E\u5B9E\u9700\u8981\u9009\u53D6\u67D0\u4E2A\u6587\u4EF6\u65F6\uFF0C\u624D\u8C03\u7528 cheso_project_files\u3002\u521B\u5EFA\u6210\u529F\u540E\u7528\u8FD4\u56DE\u7684 task_id \u8C03\u7528\u4E00\u6B21 cheso_wait \u7B49\u5F85\u7ED3\u679C\u3002\u4EFB\u52A1\u6309\u7528\u6237\u7684 Cheso \u8D26\u53F7\u4E0E\u79EF\u5206\u6267\u884C\u3002",
1038
1370
  parameters: {
1039
1371
  prompt: {
1040
1372
  type: "string",
1041
- required: true,
1042
- description: "\u9010\u5B57\u4F20\u5165\u7528\u6237\u7684\u4EFB\u52A1\u539F\u8BDD\u3002\u53EA\u5728\u7528\u6237\u660E\u786E\u5F15\u7528\u524D\u6587\u65F6\u9644\u4E0A\u7528\u6237\u63D0\u4F9B\u6216\u786E\u8BA4\u7684\u76F8\u5173\u539F\u6587\u3002\u4E0D\u8981\u6539\u5199\uFF0C\u4E5F\u4E0D\u8981\u8865\u5145\u53D7\u4F17\u3001\u8BED\u8A00\u3001\u98CE\u683C\u3001\u5927\u7EB2\u3001\u8F93\u51FA\u683C\u5F0F\u6216\u5176\u4ED6\u672A\u6307\u5B9A\u7684\u4FE1\u606F\u3002"
1373
+ description: "\u65B0\u5EFA\u65F6\u5FC5\u987B\u9010\u5B57\u4F20\u5165\u7528\u6237\u7684\u4EFB\u52A1\u539F\u8BDD\u3002\u53EA\u5728\u7528\u6237\u660E\u786E\u5F15\u7528\u524D\u6587\u65F6\u9644\u4E0A\u7528\u6237\u63D0\u4F9B\u6216\u786E\u8BA4\u7684\u76F8\u5173\u539F\u6587\u3002\u4E0D\u8981\u6539\u5199\uFF0C\u4E5F\u4E0D\u8981\u8865\u5145\u53D7\u4F17\u3001\u8BED\u8A00\u3001\u98CE\u683C\u3001\u5927\u7EB2\u3001\u8F93\u51FA\u683C\u5F0F\u6216\u5176\u4ED6\u672A\u6307\u5B9A\u7684\u4FE1\u606F\u3002"
1043
1374
  },
1044
- files: { type: "array", items: { type: "string" }, description: "\u8981\u4F5C\u4E3A\u53C2\u8003\u7684\u672C\u5730\u6587\u4EF6\u8DEF\u5F84\u3002" },
1375
+ files: { type: "array", items: { type: "string" }, description: "\u7528\u6237\u6307\u5B9A\u7684\u53C2\u8003\u9644\u4EF6\u540D\u79F0\u6216\u8DEF\u5F84\u3002\u76F4\u63A5\u9644\u52A0\u5728\u5F53\u524D\u6D88\u606F\u4E2D\u7684\u6587\u4EF6\u53EF\u6309\u540D\u79F0\u5F15\u7528\uFF1B\u5176\u5B83\u672C\u5730\u6587\u4EF6\u9700\u8981\u7528\u6237\u786E\u8BA4\u4E0A\u4F20\u3002" },
1045
1376
  project_id: { type: "string", description: "\u7EE7\u7EED\u5728\u5DF2\u6709 Cheso \u9879\u76EE\u4E2D\u521B\u5EFA\u6216\u4FEE\u6539\u4EA7\u7269\u65F6\uFF0C\u4F20\u5165\u7528\u6237\u63D0\u4F9B\u7684\u9879\u76EE ID \u6216\u5B8C\u6574\u9879\u76EE\u94FE\u63A5\u3002" },
1377
+ follow_up_task_id: { type: "string", description: "\u7ED9 Cheso \u5BF9\u8BDD\u53D1\u9001\u66F4\u6B63\u6216\u8865\u5145\u6D88\u606F\u65F6\uFF0C\u4F20\u5165 cheso_create \u6216 cheso_wait \u8FD4\u56DE\u7684\u5F53\u524D\u4EFB\u52A1 ID\u3002" },
1378
+ task_site: { type: "string", description: "\u539F\u4EFB\u52A1\u6216\u6388\u6743\u5361\u4E2D\u7684 base_url\u3002\u7701\u7565\u65F6\uFF0C\u65B0\u8BF7\u6C42\u4F7F\u7528\u5F53\u524D\u7AD9\u70B9\u3002" },
1379
+ retry_call_id: { type: "string", description: "\u6388\u6743\u5B8C\u6210\u540E\u7EE7\u7EED\u521B\u5EFA\u65F6\uFF0C\u53EA\u4F20\u4E4B\u524D login_required \u7ED3\u679C\u7684 retry_call_id\uFF0C\u63D2\u4EF6\u4F1A\u6062\u590D\u539F\u8BF7\u6C42\u3002" },
1046
1380
  agent_type: { type: "string", description: "cheso\uFF08\u9ED8\u8BA4\uFF09\u6216 image_edit\u3002" }
1047
1381
  },
1048
1382
  output: {
1049
1383
  schema: artifactCardSchema,
1050
1384
  render: (_args, value) => renderCard(
1051
1385
  value,
1052
- value.status === "login_required" ? "\u9700\u8981\u767B\u5F55 Cheso" : value.status === "insufficient_credits" ? "Cheso \u79EF\u5206\u4E0D\u8DB3" : `Cheso \u4EFB\u52A1 ${value.task_id ?? ""}\uFF1A${value.status ?? ""}`
1386
+ value.status === "login_required" ? DSH_LOGIN_REQUIRED : value.status === "insufficient_credits" ? "Cheso \u79EF\u5206\u4E0D\u8DB3" : `Cheso \u4EFB\u52A1 ${value.task_id ?? ""}\uFF1A${value.status ?? ""}`
1053
1387
  )
1054
1388
  },
1055
1389
  /** 检查积分、上传参考附件并创建任务,同时记住任务所属站点。 */
1056
- async execute({ prompt, files, project_id, agent_type }, exec) {
1057
- const config = currentConfig();
1390
+ async execute({ retry_call_id, task_site, ...input }, exec) {
1391
+ const session = exec.agent?.session;
1392
+ const retries = session && createRetries.get(session);
1393
+ const retry = retry_call_id ? retries?.get(retry_call_id) : void 0;
1394
+ if (retry_call_id && !retry) throw new Error("\u539F\u521B\u5EFA\u8BF7\u6C42\u5DF2\u4E0D\u53EF\u6062\u590D\u6216\u5DF2\u5904\u7406\uFF0C\u8BF7\u6838\u5BF9\u4EFB\u52A1\u72B6\u6001\uFF1B\u5982\u9700\u91CD\u65B0\u521B\u5EFA\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u9700\u6C42\u548C\u9644\u4EF6\u3002");
1395
+ if (retry?.inFlight) throw new Error("\u539F\u521B\u5EFA\u8BF7\u6C42\u6B63\u5728\u91CD\u8BD5\u3002");
1396
+ if (retry && (task_site !== void 0 && task_site !== retry.baseUrl || Object.entries(input).some(([key, value]) => value !== void 0 && JSON.stringify(value) !== JSON.stringify(retry.request[key])))) {
1397
+ throw new Error("\u91CD\u8BD5\u987B\u6CBF\u7528\u539F\u7AD9\u70B9\u548C\u539F\u8BF7\u6C42\u3002");
1398
+ }
1399
+ const request = retry?.request ?? input;
1400
+ const { prompt, files, project_id, follow_up_task_id, agent_type } = request;
1401
+ if (!prompt?.trim()) throw new Error("\u8BF7\u63D0\u4F9B\u4EFB\u52A1\u9700\u6C42\u3002");
1402
+ const site = retry?.baseUrl ?? task_site;
1403
+ const followedTask = follow_up_task_id ? routeTask(follow_up_task_id, site, exec.agent) : void 0;
1404
+ const config = followedTask?.config ?? configForSite(site);
1405
+ if (!config) throw new Error(unknownSite);
1406
+ const agentType = followedTask?.agentType || agent_type || void 0;
1407
+ const attachmentBlocks = retry?.attachmentBlocks ?? (files?.length ? userAttachmentBlocks(exec.agent) : []);
1058
1408
  const signal = exec.signal;
1409
+ let waitingForLogin = false;
1410
+ if (retry) retry.inFlight = true;
1059
1411
  try {
1060
- if (!prompt.trim()) throw new Error("\u8BF7\u63D0\u4F9B\u4EFB\u52A1\u9700\u6C42\u3002");
1061
- const projectId = project_id ? projectIdFromReference(project_id, config.baseUrl) : void 0;
1062
- const balance = await config.api.credits(signal).catch((error) => {
1063
- signal?.throwIfAborted();
1064
- if (error instanceof LoginRequired) throw error;
1065
- return void 0;
1066
- });
1067
- if (balance !== void 0 && balance <= 0) {
1068
- return { status: "insufficient_credits", message: "Cheso \u79EF\u5206\u4E0D\u8DB3\u3002", embed_base_url: config.embedBaseUrl };
1069
- }
1070
- const attachments = [];
1071
- if (files?.length) {
1072
- const cwd = await ctx.workingDirectory.ensure(exec.agent, signal);
1073
- for (const filename of files) {
1074
- attachments.push(await uploadAttachment(config.api, path2.resolve(cwd, filename), projectId, signal));
1412
+ let projectId = project_id ? projectIdFromReference(project_id, config.baseUrl) : void 0;
1413
+ let sessionId;
1414
+ if (follow_up_task_id) {
1415
+ const task = await config.api.request(
1416
+ `/api/v1/plans/${chesoId(follow_up_task_id)}`,
1417
+ { signal }
1418
+ );
1419
+ if (!task.project_id || !task.session_id) throw new Error("Cheso \u672A\u8FD4\u56DE\u539F\u4EFB\u52A1\u7684\u9879\u76EE\u6216\u5BF9\u8BDD ID\u3002");
1420
+ if (projectId && task.project_id !== projectId) {
1421
+ throw new Error("\u8865\u5145\u6D88\u606F\u5FC5\u987B\u53D1\u5230\u539F\u4EFB\u52A1\u6240\u5C5E\u7684 Cheso \u9879\u76EE\u3002");
1422
+ }
1423
+ projectId = task.project_id;
1424
+ sessionId = task.session_id;
1425
+ } else {
1426
+ const balance = await config.api.credits(signal).catch((error) => {
1427
+ signal?.throwIfAborted();
1428
+ if (error instanceof LoginRequired || error instanceof FixedTokenRejected) throw error;
1429
+ return void 0;
1430
+ });
1431
+ if (balance !== void 0 && balance <= 0) {
1432
+ return { status: "insufficient_credits", message: "Cheso \u79EF\u5206\u4E0D\u8DB3\u3002", embed_base_url: config.embedBaseUrl };
1075
1433
  }
1076
1434
  }
1077
- const created = await config.api.request(
1435
+ const attachments = files?.length ? await uploadAttachments(ctx, config.api, files, sessionId ? void 0 : projectId, exec, attachmentBlocks) : [];
1436
+ let created = await config.api.request(
1078
1437
  "/api/v1/plans/create",
1079
1438
  {
1080
1439
  body: {
1081
1440
  prompt,
1082
1441
  project_id: projectId,
1083
- agent_type: agent_type || void 0,
1442
+ agent_type: agentType,
1443
+ ...sessionId ? { session_id: sessionId, on_running: "queue" } : {},
1084
1444
  contexts: attachments.length ? attachments.map((file_id) => ({ file_id, category: "attachment" })) : void 0
1085
1445
  },
1086
1446
  signal,
1087
1447
  timeoutMs: 6e4
1088
1448
  }
1089
1449
  );
1450
+ if (created.queued && projectId) {
1451
+ const projectFields = { project_id: projectId, project_url: config.api.projectUrl(projectId) };
1452
+ const messageId = created.message?.message_id;
1453
+ if (!messageId) {
1454
+ return cardPayload({ ...projectFields, status: "queued", message: "Cheso \u5DF2\u63A5\u6536\u8865\u5145\u6D88\u606F\uFF0C\u53EF\u5728\u539F\u9879\u76EE\u67E5\u770B\u961F\u5217\u3002" }, config);
1455
+ }
1456
+ try {
1457
+ created = await config.api.request("/api/v1/messages/send_now", { body: { message_id: messageId }, signal });
1458
+ } catch (error) {
1459
+ signal?.throwIfAborted();
1460
+ const code = error instanceof ChesoApiError ? error.code : void 0;
1461
+ const queued = code !== void 0 && [2410, 2614, 2620, 2624, 3203, 3204].includes(code);
1462
+ const message = code === 2410 ? "\u8865\u5145\u6D88\u606F\u5DF2\u6392\u961F\u3002\u5F53\u524D Cheso \u6388\u6743\u672A\u5F00\u653E\u7ACB\u5373\u53D1\u9001\uFF0C\u53EF\u5728\u539F\u9879\u76EE\u5904\u7406\u3002" : queued ? "\u8865\u5145\u6D88\u606F\u5DF2\u6392\u961F\uFF0C\u53EF\u5728\u539F\u9879\u76EE\u67E5\u770B\u3002" : "Cheso \u5DF2\u63A5\u6536\u8865\u5145\u6D88\u606F\uFF0C\u6682\u672A\u786E\u8BA4\u7ACB\u5373\u53D1\u9001\u7ED3\u679C\u3002\u8BF7\u5728\u539F\u9879\u76EE\u67E5\u770B\u6D88\u606F\u72B6\u6001\u3002";
1463
+ return cardPayload({ ...projectFields, status: queued ? "queued" : "unknown", message }, config);
1464
+ }
1465
+ if (!created.plan_id) {
1466
+ return cardPayload({ ...projectFields, status: "unknown", message: "Cheso \u5DF2\u63A5\u6536\u8865\u5145\u6D88\u606F\uFF0C\u8BF7\u5728\u539F\u9879\u76EE\u67E5\u770B\u6D88\u606F\u72B6\u6001\u3002" }, config);
1467
+ }
1468
+ }
1090
1469
  if (!created.plan_id) throw new Error("Cheso \u672A\u8FD4\u56DE\u4EFB\u52A1 ID\u3002");
1091
1470
  const project = created.project_id || projectId;
1092
- pendingTasks.set(created.plan_id, { config, projectId: project });
1471
+ const previousTaskId = created.plan_status === "pending" ? followedTask?.previousTaskId ?? follow_up_task_id : void 0;
1472
+ const route = { config, projectId: project, agentType, previousTaskId };
1473
+ pendingTasks.set(routingKey(config, created.plan_id), route);
1474
+ rememberTask(created.plan_id, route);
1093
1475
  return cardPayload({
1094
1476
  task_id: created.plan_id,
1477
+ previous_task_id: previousTaskId,
1095
1478
  status: created.plan_status || "in_progress",
1096
1479
  project_id: project,
1097
1480
  project_url: project ? config.api.projectUrl(project) : void 0
1098
1481
  }, config);
1099
1482
  } catch (error) {
1483
+ if (error instanceof LoginRequired && session) {
1484
+ const retryId = retry_call_id ?? randomUUID2();
1485
+ const sessionRetries = retries ?? /* @__PURE__ */ new Map();
1486
+ sessionRetries.set(retryId, { request, baseUrl: config.baseUrl, attachmentBlocks });
1487
+ if (!retries) createRetries.set(session, sessionRetries);
1488
+ waitingForLogin = true;
1489
+ return { ...toolFailure(error, config), retry_call_id: retryId };
1490
+ }
1100
1491
  return toolFailure(error, config);
1492
+ } finally {
1493
+ if (retry_call_id && !waitingForLogin) retries?.delete(retry_call_id);
1101
1494
  }
1102
1495
  }
1103
1496
  })
@@ -1105,51 +1498,77 @@ function apply(ctx, pluginConfig) {
1105
1498
  ctx.tools.register(
1106
1499
  defineTool({
1107
1500
  name: "cheso_wait",
1108
- description: "\u7B49\u5F85 Cheso \u4EFB\u52A1\u5B8C\u6210\u3002\u8FD4\u56DE running \u65F6\uFF0C\u7528\u540C\u4E00\u4E2A\u4EFB\u52A1 ID \u7EE7\u7EED\u7B49\u5F85\uFF0C\u540C\u4E00\u4EFB\u52A1\u4E00\u6B21\u53EA\u8C03\u7528\u4E00\u4E2A cheso_wait\u3002\u6BCF\u8F6E\u63D0\u95EE\uFF08\u5305\u62EC\u8FFD\u95EE\u548C\u4FEE\u6539\u540E\u7684\u518D\u6B21\u786E\u8BA4\uFF09\u90FD\u7531\u672C\u5DE5\u5177\u5C55\u793A Cheso \u539F\u9898\u3002\u7528\u6237\u56DE\u7B54\u3001\u8DF3\u8FC7\u6216 Cheso \u7ED3\u675F\u63D0\u95EE\u540E\uFF0C\u7EE7\u7EED\u7B49\u5F85\u540C\u4E00\u4EFB\u52A1\u3002\u65E0\u9700\u53E6\u884C\u53D1\u8D77\u95EE\u7B54\u6216\u8F6C\u53D1\u7B54\u6848\u3002\u4E0D\u5F97\u4EE3\u7B54\u3001\u4EE3\u4E3A\u8DF3\u8FC7\uFF0C\u6216\u5C06\u5148\u524D\u7B54\u590D\u89C6\u4E3A\u5BF9\u65B0\u95EE\u9898\u7684\u786E\u8BA4\u3002\u5982\u679C\u8FD4\u56DE interact\uFF0C\u7ED3\u675F\u5F53\u524D\u56DE\u5408\uFF1B\u8BF7\u7528\u6237\u5230 Cheso \u9879\u76EE\u5904\u7406\uFF0C\u7B49\u7528\u6237\u786E\u8BA4\u540E\u518D\u7EE7\u7EED\u7B49\u5F85\u3002\u4EFB\u52A1\u5B8C\u6210\u540E\u8FD4\u56DE\u5728\u7EBF\u4EA7\u7269\u5361\u548C Cheso \u9879\u76EE\u94FE\u63A5\uFF0C\u76F4\u63A5\u7528\u5B83\u4EEC\u4EA4\u4ED8\u3002\u4EA7\u7269\u4FDD\u5B58\u5728 Cheso\u3002",
1501
+ description: "\u7B49\u5F85 Cheso \u4EFB\u52A1\u5B8C\u6210\u3002\u8FD4\u56DE running \u65F6\uFF0C\u7528\u540C\u4E00\u4E2A\u4EFB\u52A1 ID \u7EE7\u7EED\u7B49\u5F85\uFF0C\u540C\u4E00\u4EFB\u52A1\u4E00\u6B21\u53EA\u8C03\u7528\u4E00\u4E2A cheso_wait\u3002\u8FD4\u56DE terminated \u65F6\uFF0C\u76F4\u63A5\u603B\u7ED3\u505C\u6B62\u72B6\u6001\u548C\u4EFB\u52A1\u7ED3\u679C\u786E\u8BA4\u7684\u6210\u54C1\u3002\u6536\u5230\u7528\u6237\u63D2\u8BDD\u65F6\u63D0\u524D\u8FD4\u56DE\u3002\u7528\u6237\u8981\u6C42\u505C\u6B62\u4EFB\u52A1\u65F6\u8C03\u7528 cheso_stop\u3002\u7528\u6237\u66F4\u6B63\u6216\u8865\u5145\u4EFB\u52A1\u9700\u6C42\u65F6\uFF0C\u7528 cheso_create \u7684 follow_up_task_id \u628A\u6D88\u606F\u53D1\u5230\u539F\u5BF9\u8BDD\u3002\u6BCF\u8F6E\u63D0\u95EE\uFF08\u5305\u62EC\u8FFD\u95EE\u548C\u4FEE\u6539\u540E\u7684\u518D\u6B21\u786E\u8BA4\uFF09\u90FD\u7531\u672C\u5DE5\u5177\u5C55\u793A Cheso \u539F\u9898\u3002\u7528\u6237\u56DE\u7B54\u3001\u8DF3\u8FC7\u6216 Cheso \u7ED3\u675F\u63D0\u95EE\u540E\uFF0C\u7EE7\u7EED\u7B49\u5F85\u540C\u4E00\u4EFB\u52A1\u3002\u65E0\u9700\u53E6\u884C\u53D1\u8D77\u95EE\u7B54\u6216\u8F6C\u53D1\u7B54\u6848\u3002\u4E0D\u5F97\u4EE3\u7B54\u3001\u4EE3\u4E3A\u8DF3\u8FC7\uFF0C\u6216\u5C06\u5148\u524D\u7B54\u590D\u89C6\u4E3A\u5BF9\u65B0\u95EE\u9898\u7684\u786E\u8BA4\u3002\u5982\u679C\u8FD4\u56DE interact\uFF0C\u7ED3\u675F\u5F53\u524D\u56DE\u5408\uFF1B\u8BF7\u7528\u6237\u5230 Cheso \u9879\u76EE\u5904\u7406\uFF0C\u7B49\u7528\u6237\u786E\u8BA4\u540E\u518D\u7EE7\u7EED\u7B49\u5F85\u3002\u4EFB\u52A1\u5B8C\u6210\u540E\u8FD4\u56DE\u5728\u7EBF\u4EA7\u7269\u5361\u548C Cheso \u9879\u76EE\u94FE\u63A5\uFF0C\u76F4\u63A5\u7528\u5B83\u4EEC\u4EA4\u4ED8\u3002\u4EA7\u7269\u4FDD\u5B58\u5728 Cheso\u3002",
1109
1502
  parameters: {
1110
1503
  task_id: { type: "string", required: true, description: "cheso_create \u8FD4\u56DE\u7684 task_id\u3002" },
1504
+ task_site: { type: "string", description: "\u539F\u4EFB\u52A1\u7ED3\u679C\u4E2D\u7684 base_url\uFF08\u5982\u6709\uFF09\u3002" },
1111
1505
  timeout_sec: { type: "number", description: "\u6BCF\u6BB5\u8F6E\u8BE2\u7684\u7B49\u5F85\u4E0A\u9650\uFF0C\u4E0D\u542B\u7528\u6237\u56DE\u7B54\u65F6\u95F4\uFF0C\u9ED8\u8BA4\u4F7F\u7528\u63D2\u4EF6\u914D\u7F6E\u3002" }
1112
1506
  },
1113
1507
  output: {
1114
1508
  schema: waitCardSchema,
1115
1509
  presentationMeta: (_args, { question_receipts }) => question_receipts?.length ? { cheso_question_receipts: question_receipts } : null,
1116
- render: (_args, { question_receipts: _receipts, ...value }) => renderCard(
1117
- value,
1118
- value.status === "login_required" ? "\u9700\u8981\u767B\u5F55 Cheso" : value.status === "insufficient_credits" ? "Cheso \u79EF\u5206\u4E0D\u8DB3" : `Cheso \u4EFB\u52A1 ${value.task_id ?? ""}\uFF1A${value.status ?? ""}`
1119
- )
1510
+ render: (_args, { question_receipts: _receipts, ...value }) => {
1511
+ if (value.status === "terminated") {
1512
+ return renderCard(value, STOP_SUMMARY);
1513
+ }
1514
+ return renderCard(
1515
+ value,
1516
+ value.status === "login_required" ? DSH_LOGIN_REQUIRED : value.status === "insufficient_credits" ? "Cheso \u79EF\u5206\u4E0D\u8DB3" : `Cheso \u4EFB\u52A1 ${value.task_id ?? ""}\uFF1A${value.status ?? ""}`
1517
+ );
1518
+ }
1120
1519
  },
1121
1520
  /** 继续轮询原站点上的任务,处理每轮提问并保留已提交的答复记录。 */
1122
- async execute({ task_id, timeout_sec }, exec) {
1123
- let pending = pendingTasks.get(task_id) ?? { config: currentConfig() };
1521
+ async execute({ task_id, task_site, timeout_sec }, exec) {
1522
+ let pending = routeTask(task_id, task_site, exec.agent);
1124
1523
  const { config } = pending;
1125
1524
  let current = task_id;
1126
1525
  const activity = { previews: null, receipts: [] };
1127
1526
  receiptsByExecution.set(exec, activity.receipts);
1128
1527
  if (exec.callId) waitQuestionActivity.set(exec.callId, activity);
1129
1528
  const receiptFields = () => activity.receipts.length ? { question_receipts: activity.receipts } : {};
1529
+ const steering = new AbortController();
1530
+ const waitSignal = exec.signal ? AbortSignal.any([exec.signal, steering.signal]) : steering.signal;
1531
+ const agent = exec.agent;
1532
+ const checkSteering = () => {
1533
+ if (agent?.inbox?.nextStep.some((message) => message.source.kind === "user")) steering.abort();
1534
+ };
1535
+ const offInbox = agent && ctx.on("agent/inbox/inserted", ({ agent: recipient }) => {
1536
+ if (recipient === agent) checkSteering();
1537
+ });
1130
1538
  try {
1539
+ checkSteering();
1131
1540
  const timeout = Math.min(Math.max(Number(timeout_sec) || config.timeoutSec, 10), 1800);
1132
1541
  for (; ; ) {
1133
1542
  const repliedQuestion = pending.repliedQuestion;
1134
- const result = await waitForTask(config.api, current, timeout, pending.projectId, exec.signal, repliedQuestion);
1543
+ const result = await waitForTask(config.api, current, timeout, pending.projectId, waitSignal, repliedQuestion, (id, activeId) => {
1544
+ current = id;
1545
+ pending = pendingTasks.get(routingKey(config, id)) ?? pending;
1546
+ if (activeId) pending.previousTaskId = activeId;
1547
+ rememberTask(id, pending);
1548
+ });
1549
+ if (result.status === "terminated") exec.signal?.throwIfAborted();
1550
+ else waitSignal.throwIfAborted();
1135
1551
  current = result.task_id;
1136
- const routedTask = pendingTasks.get(current);
1137
- if (routedTask?.config === config) pending = routedTask;
1552
+ const routedTask = pendingTasks.get(routingKey(config, current));
1553
+ if (routedTask) pending = routedTask;
1554
+ pending.projectId = result.project_id ?? pending.projectId;
1555
+ rememberTask(task_id, pending);
1556
+ rememberTask(current, pending);
1138
1557
  if (result.done) {
1139
- for (const [id, task] of pendingTasks) {
1140
- if (task === pending || id === task_id || id === current) pendingTasks.delete(id);
1558
+ for (const [key, task] of pendingTasks) {
1559
+ if (task === pending || key === routingKey(config, task_id) || key === routingKey(config, current)) pendingTasks.delete(key);
1141
1560
  }
1142
1561
  } else {
1143
- pending.projectId = result.project_id;
1144
- pendingTasks.set(task_id, pending);
1145
- pendingTasks.set(current, pending);
1562
+ pendingTasks.set(routingKey(config, task_id), pending);
1563
+ pendingTasks.set(routingKey(config, current), pending);
1146
1564
  if (result.status === "running" && pending.repliedQuestion === repliedQuestion) {
1147
1565
  pending.repliedQuestion = result.repliedQuestion;
1148
1566
  }
1149
1567
  }
1568
+ if (result.status === "terminated") return await stoppedCard(result, config, exec.signal, receiptFields());
1150
1569
  const interaction = result.interaction;
1151
1570
  if (interaction && pending.repliedQuestion === interaction.key) continue;
1152
- const userQuestions = interaction?.questions.length && !pending.asking && exec.agent ? ctx.get("userQuestions") : void 0;
1571
+ const userQuestions = interaction?.questions.length && !hasDuplicateQuestions(interaction.questions) && !pending.asking && exec.agent ? ctx.get("userQuestions") : void 0;
1153
1572
  if (interaction && userQuestions) {
1154
1573
  pending.asking = true;
1155
1574
  activity.previews = interaction.previews;
@@ -1159,12 +1578,12 @@ function apply(ctx, pluginConfig) {
1159
1578
  current,
1160
1579
  interaction,
1161
1580
  (questions, signal) => userQuestions.ask({ agent: exec.agent, questions, signal }),
1162
- exec.signal
1581
+ waitSignal
1163
1582
  );
1164
- exec.signal?.throwIfAborted();
1583
+ waitSignal.throwIfAborted();
1165
1584
  if (reply === "closed") continue;
1166
1585
  if (reply) {
1167
- const submission = await replyToTask(config.api, current, interaction, reply, exec.signal);
1586
+ const submission = await replyToTask(config.api, current, interaction, reply, waitSignal, exec.signal);
1168
1587
  if (submission !== "changed") pending.repliedQuestion = interaction.key;
1169
1588
  if (typeof submission !== "string") activity.receipts.push(submission);
1170
1589
  continue;
@@ -1178,17 +1597,74 @@ function apply(ctx, pluginConfig) {
1178
1597
  return cardPayload({
1179
1598
  ...result,
1180
1599
  message,
1600
+ previous_task_id: pending.previousTaskId,
1181
1601
  project_url: result.project_id ? config.api.projectUrl(result.project_id) : void 0
1182
1602
  }, config, receiptFields());
1183
1603
  }
1184
1604
  } catch (error) {
1605
+ exec.signal?.throwIfAborted();
1606
+ if (steering.signal.aborted) {
1607
+ pendingTasks.set(routingKey(config, task_id), pending);
1608
+ pendingTasks.set(routingKey(config, current), pending);
1609
+ return cardPayload({
1610
+ task_id: current,
1611
+ status: "running",
1612
+ project_id: pending.projectId,
1613
+ previous_task_id: pending.previousTaskId,
1614
+ project_url: pending.projectId ? config.api.projectUrl(pending.projectId) : void 0,
1615
+ message: "\u5DF2\u7ED3\u675F\u672C\u6B21\u7B49\u5F85\u4EE5\u5904\u7406\u7528\u6237\u63D2\u8BDD\u3002\u8BF7\u5148\u5904\u7406\u65B0\u6D88\u606F\u3002"
1616
+ }, config, receiptFields());
1617
+ }
1185
1618
  return { ...toolFailure(error, config, current), ...receiptFields() };
1186
1619
  } finally {
1620
+ offInbox?.();
1187
1621
  if (exec.callId) waitQuestionActivity.delete(exec.callId);
1188
1622
  }
1189
1623
  }
1190
1624
  })
1191
1625
  );
1626
+ ctx.tools.register(
1627
+ defineTool({
1628
+ name: "cheso_stop",
1629
+ description: "\u7528\u6237\u8981\u6C42\u505C\u6B62 Cheso \u4EFB\u52A1\u65F6\uFF0C\u7EC8\u6B62\u8BE5\u4EFB\u52A1\u6240\u5728\u7684\u6267\u884C\u94FE\u3002\u786E\u8BA4\u7EC8\u6B62\u540E\u8FD4\u56DE\u505C\u6B62\u72B6\u6001\u53CA\u4EFB\u52A1\u7ED3\u679C\u4E2D\u7684\u6210\u54C1\u3002\u8FD4\u56DE stopping \u8868\u793A\u5DF2\u53D1\u51FA\u505C\u6B62\u8BF7\u6C42\u3002",
1630
+ parameters: {
1631
+ task_id: { type: "string", required: true, description: "\u8981\u505C\u6B62\u7684 Cheso \u4EFB\u52A1 ID\uFF0C\u6765\u81EA cheso_create \u6216 cheso_wait\u3002" },
1632
+ task_site: { type: "string", description: "\u539F\u4EFB\u52A1\u7ED3\u679C\u4E2D\u7684 base_url\uFF08\u5982\u6709\uFF09\u3002" }
1633
+ },
1634
+ output: {
1635
+ schema: artifactCardSchema,
1636
+ render: (_args, value) => {
1637
+ const { task_id, status } = value;
1638
+ if (status === "terminated") return renderCard(value, STOP_SUMMARY);
1639
+ if (status === "login_required") return renderCard(value, DSH_LOGIN_REQUIRED);
1640
+ const messages = {
1641
+ stopping: "Cheso \u5DF2\u6536\u5230\u505C\u6B62\u8BF7\u6C42\uFF0C\u6B63\u5728\u7B49\u5F85\u4EFB\u52A1\u7ED3\u675F\u3002",
1642
+ completed: "Cheso \u4EFB\u52A1\u5DF2\u5B8C\u6210\u3002",
1643
+ failed: "Cheso \u4EFB\u52A1\u5DF2\u5931\u8D25\u3002",
1644
+ rolled_back: "Cheso \u4EFB\u52A1\u5DF2\u56DE\u6EDA\u3002",
1645
+ pending: "Cheso \u6B63\u5728\u4EA4\u63A5\u4EFB\u52A1\uFF0C\u5C1A\u672A\u786E\u8BA4\u505C\u6B62\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"
1646
+ };
1647
+ return renderCard(value, `${messages[status ?? ""] ?? "\u8BF7\u68C0\u67E5 Cheso \u4EFB\u52A1\u72B6\u6001\u3002"} \u4EFB\u52A1 ID\uFF1A${task_id ?? ""}`);
1648
+ }
1649
+ },
1650
+ async execute({ task_id, task_site }, exec) {
1651
+ const task = routeTask(task_id, task_site, exec.agent);
1652
+ const { config } = task;
1653
+ try {
1654
+ const result = await stopTask(config.api, task_id, task.previousTaskId, exec.signal);
1655
+ rememberTask(result.task_id, task);
1656
+ if (result.status === "terminated") return await stoppedCard({ ...result, project_id: task.projectId }, config, exec.signal);
1657
+ return { task_id: result.task_id, status: result.status, base_url: config.baseUrl };
1658
+ } catch (error) {
1659
+ if (error instanceof LoginRequired) return toolFailure(error, config, task_id);
1660
+ if (error instanceof ChesoApiError && error.code === 2313) {
1661
+ throw new Error("\u53EA\u6709 Cheso \u4EFB\u52A1\u53D1\u8D77\u4EBA\u6216\u8BE5\u9879\u76EE\u7684\u6240\u6709\u8005\u53EF\u4EE5\u505C\u6B62\u4EFB\u52A1\u3002");
1662
+ }
1663
+ throw error;
1664
+ }
1665
+ }
1666
+ })
1667
+ );
1192
1668
  ctx.tools.register(
1193
1669
  defineTool({
1194
1670
  name: "cheso_project_files",
@@ -1241,10 +1717,7 @@ function apply(ctx, pluginConfig) {
1241
1717
  expires_at: { type: "number" }
1242
1718
  }
1243
1719
  },
1244
- render: (_args, value) => renderCard(
1245
- value,
1246
- "Cheso \u6388\u6743\u5361\u5DF2\u663E\u793A\u3002\u8BF7\u7528\u6237\u5728\u6D4F\u89C8\u5668\u5B8C\u6210\u6388\u6743\uFF0C\u7136\u540E\u56DE\u5230 DSH \u68C0\u67E5\u767B\u5F55\u3002\u7B49\u5F85\u7528\u6237\u56DE\u590D\u540E\u518D\u7EE7\u7EED\u3002"
1247
- )
1720
+ render: (_args, value) => value.status === "signed_in" ? [{ type: "text", text: "Cheso \u5DF2\u767B\u5F55\u3002" }] : renderCard(value, "Cheso \u6388\u6743\u5361\u5DF2\u663E\u793A\u3002\u8BF7\u7528\u6237\u5728\u6D4F\u89C8\u5668\u5B8C\u6210\u6388\u6743\uFF0C\u7136\u540E\u56DE\u5230 DSH \u68C0\u67E5\u767B\u5F55\u3002\u7B49\u5F85\u7528\u6237\u56DE\u590D\u540E\u518D\u7EE7\u7EED\u3002")
1248
1721
  },
1249
1722
  /** 为当前站点发起授权,生成对话登录卡所需的数据。 */
1250
1723
  async execute(_args, exec) {
@@ -1257,6 +1730,7 @@ function apply(ctx, pluginConfig) {
1257
1730
  name: "cheso_login_wait",
1258
1731
  description: "\u7528\u6237\u786E\u8BA4\u5DF2\u5728\u6D4F\u89C8\u5668\u6388\u6743\u540E\uFF0C\u77ED\u6682\u68C0\u67E5\u767B\u5F55\u7ED3\u679C\u3002\u82E5\u4ECD\u5F85\u6388\u6743\uFF0C\u63D0\u793A\u7528\u6237\u5728\u6388\u6743\u5361\u4E2D\u5B8C\u6210\u64CD\u4F5C\u5E76\u7ED3\u675F\u56DE\u590D\u3002",
1259
1732
  parameters: {
1733
+ base_url: { type: "string", description: "\u672C\u6B21\u6388\u6743\u5361\u4E2D\u7684 base_url\u3002\u7701\u7565\u65F6\u4F7F\u7528\u5F53\u524D\u5BF9\u8BDD\u6700\u8FD1\u4E00\u5F20\u6388\u6743\u5361\u3002" },
1260
1734
  timeout_sec: { type: "number", description: "\u517C\u5BB9\u65E7\u8C03\u7528\uFF1B\u6B64\u5DE5\u5177\u53EA\u505A\u77ED\u6682\u68C0\u67E5\u3002" }
1261
1735
  },
1262
1736
  output: {
@@ -1270,9 +1744,11 @@ function apply(ctx, pluginConfig) {
1270
1744
  text: value.status === "signed_in" ? "Cheso \u5DF2\u767B\u5F55\u3002" : "Cheso \u5C1A\u672A\u5B8C\u6210\u6388\u6743\uFF0C\u8BF7\u5728\u6388\u6743\u5361\u4E2D\u7EE7\u7EED\u64CD\u4F5C\u3002"
1271
1745
  }]
1272
1746
  },
1273
- /** 检查当前站点的授权结果,供用户完成浏览器授权后调用。 */
1274
- async execute(_args, exec) {
1275
- return checkLogin(currentConfig(), exec.signal);
1747
+ /** 在登录卡所属站点确认授权。 */
1748
+ async execute({ base_url }, exec) {
1749
+ const config = configForSite(base_url ?? historicalLoginSite(exec.agent));
1750
+ if (!config) throw new Error(unknownSite);
1751
+ return checkLogin(config, exec.signal);
1276
1752
  }
1277
1753
  })
1278
1754
  );
@@ -1303,13 +1779,13 @@ function apply(ctx, pluginConfig) {
1303
1779
  const config = currentConfig();
1304
1780
  const signal = exec.signal;
1305
1781
  try {
1306
- const { user } = await config.api.request("/api/v1/whoami", { signal });
1782
+ const { user } = await config.api.whoami(signal);
1307
1783
  const username = user?.username?.trim();
1308
1784
  const userId = user?.user_id?.trim();
1309
1785
  const account = username && userId ? `${username} (${userId})` : username || userId || "";
1310
1786
  const credits = await config.api.credits(signal).catch((error) => {
1311
1787
  signal?.throwIfAborted();
1312
- if (error instanceof LoginRequired) throw error;
1788
+ if (error instanceof LoginRequired || error instanceof FixedTokenRejected) throw error;
1313
1789
  return void 0;
1314
1790
  });
1315
1791
  return { signed_in: true, account, ...credits === void 0 ? {} : { credits } };
@@ -1389,14 +1865,17 @@ function apply(ctx, pluginConfig) {
1389
1865
  }
1390
1866
  const data = await request.json().catch(() => null);
1391
1867
  if (data?.action !== "start" && data?.action !== "check") return jsonResponse(400, { error: "\u65E0\u6548\u7684\u767B\u5F55\u64CD\u4F5C\u3002" });
1392
- const config = data.site === void 0 ? currentConfig() : previewConfigs.find((config2) => config2.baseUrl === data.site);
1868
+ const config = configForSite(data.site);
1393
1869
  if (!config) return jsonResponse(400, {
1394
1870
  code: "unknown_cheso_site",
1395
- error: "\u8BE5\u7AD9\u70B9\u5DF2\u4E0D\u5728\u63D2\u4EF6\u914D\u7F6E\u4E2D\u3002\u8BF7\u68C0\u67E5\u7AD9\u70B9\u8BBE\u7F6E\u5E76\u91CD\u65B0\u53D1\u8D77\u8BF7\u6C42\u3002"
1871
+ error: unknownSite
1396
1872
  });
1397
1873
  try {
1398
1874
  return jsonResponse(200, await (data.action === "start" ? login : checkLogin)(config, request.signal));
1399
1875
  } catch (error) {
1876
+ if (error instanceof FixedTokenRejected) {
1877
+ return jsonResponse(401, { code: error.code, error: error.message });
1878
+ }
1400
1879
  return jsonResponse(502, {
1401
1880
  ...error instanceof LoginAttemptError ? { code: error.code } : {},
1402
1881
  error: error instanceof Error ? error.message : "\u65E0\u6CD5\u8FDE\u63A5 Cheso \u6388\u6743\u670D\u52A1\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"
@@ -1425,6 +1904,7 @@ function apply(ctx, pluginConfig) {
1425
1904
  const version = Number.isSafeInteger(requestedVersion) && requestedVersion > 0 ? requestedVersion : void 0;
1426
1905
  data = await config.api.file(fileId, { ...requestOptions, version });
1427
1906
  } catch (error) {
1907
+ if (error instanceof FixedTokenRejected) return jsonResponse(401, { error: error.code });
1428
1908
  if (error instanceof LoginRequired) return jsonResponse(401, { error: "cheso_login_required" });
1429
1909
  if (error instanceof ChesoApiError && error.status === 403) return jsonResponse(403, { error: "cheso_file_forbidden" });
1430
1910
  return jsonResponse(502, { error: "download_url_failed" });