@witqq/agent-sdk 0.3.1 → 0.4.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.
@@ -41,6 +41,10 @@ var BaseAgent = class {
41
41
  state = "idle";
42
42
  abortController = null;
43
43
  config;
44
+ /** CLI session ID for persistent mode. Override in backends that support it. */
45
+ get sessionId() {
46
+ return void 0;
47
+ }
44
48
  constructor(config) {
45
49
  this.config = Object.freeze({ ...config });
46
50
  }
@@ -335,12 +339,9 @@ function _injectSDK(mock) {
335
339
  function _resetSDK() {
336
340
  sdkModule = null;
337
341
  }
338
- var CLAUDE_KNOWN_MODELS = [
339
- { id: "claude-sonnet-4-5-20250514", name: "Claude Sonnet 4.5" },
340
- { id: "claude-haiku-3-5-20241022", name: "Claude 3.5 Haiku" },
341
- { id: "claude-opus-4-20250514", name: "Claude Opus 4" },
342
- { id: "claude-sonnet-4-20250514", name: "Claude Sonnet 4" }
343
- ];
342
+ var ANTHROPIC_MODELS_URL = "https://api.anthropic.com/v1/models";
343
+ var ANTHROPIC_API_VERSION = "2023-06-01";
344
+ var ANTHROPIC_OAUTH_BETA = "oauth-2025-04-20";
344
345
  function buildMcpServer(sdk, tools, toolResultCapture) {
345
346
  if (tools.length === 0) return void 0;
346
347
  const mcpTools = tools.map(
@@ -584,17 +585,27 @@ var ClaudeAgent = class extends BaseAgent {
584
585
  options;
585
586
  tools;
586
587
  canUseTool;
588
+ isPersistent;
589
+ _sessionId;
587
590
  constructor(config, options) {
588
591
  super(config);
589
592
  this.options = options;
590
593
  this.tools = config.tools;
591
594
  this.canUseTool = buildCanUseTool(config);
595
+ this.isPersistent = config.sessionMode === "persistent";
592
596
  if (config.supervisor?.onAskUser) {
593
597
  console.warn(
594
598
  "[agent-sdk/claude] supervisor.onAskUser is not supported by the Claude CLI backend. User interaction requests from the model will not be forwarded."
595
599
  );
596
600
  }
597
601
  }
602
+ get sessionId() {
603
+ return this._sessionId;
604
+ }
605
+ /** Clear persistent session state after an error so next call starts fresh */
606
+ clearPersistentSession() {
607
+ this._sessionId = void 0;
608
+ }
598
609
  buildQueryOptions(signal) {
599
610
  const ac = new AbortController();
600
611
  signal.addEventListener("abort", () => ac.abort(), { once: true });
@@ -604,13 +615,19 @@ var ClaudeAgent = class extends BaseAgent {
604
615
  maxTurns: this.options.maxTurns,
605
616
  cwd: this.options.workingDirectory,
606
617
  pathToClaudeCodeExecutable: this.options.cliPath,
607
- persistSession: false,
618
+ persistSession: this.isPersistent,
608
619
  includePartialMessages: true,
609
620
  canUseTool: this.canUseTool
610
621
  };
622
+ if (this.isPersistent && this._sessionId) {
623
+ opts.resume = this._sessionId;
624
+ }
611
625
  if (this.config.systemPrompt) {
612
626
  opts.systemPrompt = this.config.systemPrompt;
613
627
  }
628
+ if (this.options.oauthToken) {
629
+ opts.env = { ...process.env, CLAUDE_CODE_OAUTH_TOKEN: this.options.oauthToken };
630
+ }
614
631
  return opts;
615
632
  }
616
633
  async buildMcpConfig(opts, toolResultCapture) {
@@ -628,7 +645,8 @@ var ClaudeAgent = class extends BaseAgent {
628
645
  async executeRun(messages, _options, signal) {
629
646
  this.checkAbort(signal);
630
647
  const sdk = await loadSDK();
631
- const prompt = extractLastUserPrompt(messages);
648
+ const isResuming = this.isPersistent && this._sessionId !== void 0;
649
+ const prompt = isResuming ? extractLastUserPrompt(messages) : buildContextualPrompt(messages);
632
650
  let opts = this.buildQueryOptions(signal);
633
651
  const toolResultCapture = /* @__PURE__ */ new Map();
634
652
  opts = await this.buildMcpConfig(opts, toolResultCapture);
@@ -667,6 +685,9 @@ var ClaudeAgent = class extends BaseAgent {
667
685
  const r = msg;
668
686
  output = r.result;
669
687
  usage = aggregateUsage(r.modelUsage);
688
+ if (this.isPersistent && r.session_id) {
689
+ this._sessionId = r.session_id;
690
+ }
670
691
  } else if (msg.is_error) {
671
692
  const r = msg;
672
693
  throw new Error(
@@ -676,6 +697,7 @@ var ClaudeAgent = class extends BaseAgent {
676
697
  }
677
698
  }
678
699
  } catch (e) {
700
+ if (this.isPersistent) this.clearPersistentSession();
679
701
  if (signal.aborted) throw new AbortError();
680
702
  throw e;
681
703
  }
@@ -694,7 +716,8 @@ var ClaudeAgent = class extends BaseAgent {
694
716
  async executeRunStructured(messages, schema, _options, signal) {
695
717
  this.checkAbort(signal);
696
718
  const sdk = await loadSDK();
697
- const prompt = extractLastUserPrompt(messages);
719
+ const isResuming = this.isPersistent && this._sessionId !== void 0;
720
+ const prompt = isResuming ? extractLastUserPrompt(messages) : buildContextualPrompt(messages);
698
721
  let opts = this.buildQueryOptions(signal);
699
722
  opts = await this.buildMcpConfig(opts);
700
723
  const jsonSchema = zodToJsonSchema(schema.schema);
@@ -730,6 +753,9 @@ var ClaudeAgent = class extends BaseAgent {
730
753
  }
731
754
  }
732
755
  usage = aggregateUsage(r.modelUsage);
756
+ if (this.isPersistent && r.session_id) {
757
+ this._sessionId = r.session_id;
758
+ }
733
759
  } else if (msg.type === "result" && msg.is_error) {
734
760
  const r = msg;
735
761
  throw new Error(
@@ -738,6 +764,7 @@ var ClaudeAgent = class extends BaseAgent {
738
764
  }
739
765
  }
740
766
  } catch (e) {
767
+ if (this.isPersistent) this.clearPersistentSession();
741
768
  if (signal.aborted) throw new AbortError();
742
769
  throw e;
743
770
  }
@@ -756,7 +783,8 @@ var ClaudeAgent = class extends BaseAgent {
756
783
  async *executeStream(messages, _options, signal) {
757
784
  this.checkAbort(signal);
758
785
  const sdk = await loadSDK();
759
- const prompt = extractLastUserPrompt(messages);
786
+ const isResuming = this.isPersistent && this._sessionId !== void 0;
787
+ const prompt = isResuming ? extractLastUserPrompt(messages) : buildContextualPrompt(messages);
760
788
  let opts = this.buildQueryOptions(signal);
761
789
  opts = await this.buildMcpConfig(opts);
762
790
  const q = sdk.query({ prompt, options: opts });
@@ -775,15 +803,20 @@ var ClaudeAgent = class extends BaseAgent {
775
803
  }
776
804
  if (msg.type === "result" && msg.subtype === "success") {
777
805
  const r = msg;
806
+ if (this.isPersistent && r.session_id) {
807
+ this._sessionId = r.session_id;
808
+ }
778
809
  yield { type: "done", finalOutput: r.result };
779
810
  }
780
811
  }
781
812
  } catch (e) {
813
+ if (this.isPersistent) this.clearPersistentSession();
782
814
  if (signal.aborted) throw new AbortError();
783
815
  throw e;
784
816
  }
785
817
  }
786
818
  dispose() {
819
+ this._sessionId = void 0;
787
820
  super.dispose();
788
821
  }
789
822
  };
@@ -796,6 +829,20 @@ function extractLastUserPrompt(messages) {
796
829
  }
797
830
  return "";
798
831
  }
832
+ function buildContextualPrompt(messages) {
833
+ if (messages.length <= 1) {
834
+ return extractLastUserPrompt(messages);
835
+ }
836
+ const history = messages.slice(0, -1).map((msg) => {
837
+ const text = msg.content ? getTextContent(msg.content) : "";
838
+ return msg.role === "user" ? `User: ${text}` : `Assistant: ${text}`;
839
+ }).join("\n");
840
+ const lastPrompt = extractLastUserPrompt(messages);
841
+ return `Conversation history:
842
+ ${history}
843
+
844
+ User: ${lastPrompt}`;
845
+ }
799
846
  var ClaudeAgentService = class {
800
847
  name = "claude";
801
848
  disposed = false;
@@ -811,9 +858,30 @@ var ClaudeAgentService = class {
811
858
  async listModels() {
812
859
  if (this.disposed) throw new DisposedError("ClaudeAgentService");
813
860
  if (this.cachedModels) return this.cachedModels;
814
- this.cachedModels = CLAUDE_KNOWN_MODELS.map((m) => ({
861
+ const token = this.options.oauthToken;
862
+ if (!token) {
863
+ return [];
864
+ }
865
+ const res = await globalThis.fetch(
866
+ `${ANTHROPIC_MODELS_URL}?limit=100`,
867
+ {
868
+ headers: {
869
+ Authorization: `Bearer ${token}`,
870
+ "anthropic-version": ANTHROPIC_API_VERSION,
871
+ "anthropic-beta": ANTHROPIC_OAUTH_BETA
872
+ }
873
+ }
874
+ );
875
+ if (!res.ok) {
876
+ return [];
877
+ }
878
+ const body = await res.json();
879
+ if (!body.data || body.data.length === 0) {
880
+ return [];
881
+ }
882
+ this.cachedModels = body.data.map((m) => ({
815
883
  id: m.id,
816
- name: m.name,
884
+ name: m.display_name,
817
885
  provider: "claude"
818
886
  }));
819
887
  return this.cachedModels;
@@ -834,7 +902,7 @@ var ClaudeAgentService = class {
834
902
  const q = sdk.query({
835
903
  prompt: "echo test",
836
904
  options: {
837
- model: CLAUDE_KNOWN_MODELS[0].id,
905
+ model: "claude-sonnet-4-20250514",
838
906
  pathToClaudeCodeExecutable: this.options.cliPath,
839
907
  cwd: this.options.workingDirectory,
840
908
  persistSession: false,