@runappsai/agent 0.1.3 → 0.1.5

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/dist/agent.d.ts CHANGED
@@ -148,6 +148,29 @@ export declare class Agent {
148
148
  * all of them would fit in `keepRecentTokens`.
149
149
  */
150
150
  compact(focus?: string): Promise<boolean>;
151
+ /**
152
+ * A summary of the conversation that stays out of it, to carry on in a new
153
+ * one (`seed`): everything but `leaveOut`, usually the request to send again.
154
+ * Null when there is nothing to summarise or the summary could not be written.
155
+ */
156
+ summarize(leaveOut?: ChatMessage): Promise<string | null>;
157
+ /** Starts an empty conversation from the summary of another (`summarize`). */
158
+ seed(summary: string): Promise<void>;
159
+ /** Runs like a run: messages sent meanwhile queue behind it instead of being lost when the history is replaced. */
160
+ private exclusive;
161
+ /** Settings under which everything before the latest turn may be summarised, even when all of it would fit. */
162
+ private squeezed;
163
+ /**
164
+ * The model refused the request as too large: make it smaller. Round 0
165
+ * summarises what is older than the latest turn and trims to 70% of the
166
+ * window (the estimate may run low); round 1 trims to 40%, big results of the
167
+ * latest turn included. True when the request did get smaller.
168
+ */
169
+ private squeeze;
170
+ /** What takes up the room in a request that cannot be made smaller. */
171
+ private overflowCause;
172
+ /** The summary of a cut: the host's own summariser, or the model, piece by piece. */
173
+ private writeSummary;
151
174
  private compactWith;
152
175
  /** `/skill:name args` and `/template args` in a user message. */
153
176
  private expandSlashes;
package/dist/agent.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // model answers without tools (or the run is stopped). Everything the
4
4
  // app shows comes through `on()` events; what the app owns (dialogs,
5
5
  // files, skills, tools) comes in through the options.
6
- import { errorStatus, modelAccepts, ProviderError, toProvider } from "./provider.js";
6
+ import { ContextOverflowError, errorStatus, isContextOverflow, modelAccepts, overflowLimit, ProviderError, toProvider } from "./provider.js";
7
7
  import { planCut, resolveSettings, serializeConversation, shouldCompact, splitForSummary, summaryMessage, summaryOf, summarizationMessages } from "./compaction.js";
8
8
  import { collectCompletion } from "./completion.js";
9
9
  import { buildSystemPrompt, estimateTokens, fitBudget } from "./context.js";
@@ -552,8 +552,11 @@ export class Agent {
552
552
  this._ended = null;
553
553
  this.emit("run_start", { runId, message: prefaced });
554
554
  const maxTurns = this.opts.maxTurns ?? DEFAULT_MAX_TURNS;
555
- const { output: maxTokens, input: window } = await this.limits();
556
- const compaction = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
555
+ const { output: maxTokens, input: catalogueWindow } = await this.limits();
556
+ // A refusal that states the model's real limit corrects the window for the rest of the run.
557
+ let window = catalogueWindow;
558
+ let compaction = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
559
+ let overflowRetries = 0;
557
560
  try {
558
561
  if (prefaceError)
559
562
  throw prefaceError;
@@ -617,11 +620,30 @@ export class Agent {
617
620
  const asked = Date.now();
618
621
  let completion;
619
622
  try {
623
+ // Far beyond a window the catalogue vouches for: refused without sending it.
624
+ if (estimateTokens(this.history, fixed) > window * 2 && (typeof this.opts.maxInputTokens === "number" || typeof (await this.modelInfo())?.max_input_tokens === "number")) {
625
+ throw new ProviderError(413, "the request is far larger than the model's context");
626
+ }
620
627
  completion = await this.callModel(params, runId, signal);
621
628
  }
622
629
  catch (err) {
623
630
  this.emit("response", { runId, turn, durationMs: Date.now() - asked, error: err instanceof Error ? err.message : String(err) });
624
- throw err;
631
+ if (signal.aborted || !isContextOverflow(err))
632
+ throw err;
633
+ const limit = overflowLimit(err);
634
+ if (limit !== undefined && limit < window) {
635
+ window = limit;
636
+ compaction = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
637
+ }
638
+ // Asked twice at most: first with the older turns summarised, then with nothing left but what the latest needs.
639
+ let smaller = false;
640
+ while (!smaller && overflowRetries < 2)
641
+ smaller = await this.squeeze(window, overflowRetries++, compaction, fixed, runId, signal);
642
+ if (smaller) {
643
+ turn--;
644
+ continue;
645
+ }
646
+ throw new ContextOverflowError({ cause: this.overflowCause(window, fixed), used: estimateTokens(this.history, fixed), window }, err instanceof Error ? err.message : String(err), errorStatus(err) ?? 400);
625
647
  }
626
648
  this.emit("response", { runId, turn, durationMs: Date.now() - asked, finishReason: completion.finishReason, usage: completion.usage, message: completion.message });
627
649
  if (completion.usage)
@@ -706,7 +728,8 @@ export class Agent {
706
728
  this.markRunUsage(historyBefore, usageBefore);
707
729
  this.committed = this.history.length;
708
730
  this.resetLoop();
709
- this._ended = reason === "done" ? null : { reason, ...(error ? { error: error.message } : {}), at: Date.now() };
731
+ const overflow = error instanceof ContextOverflowError ? { code: error.code, overflow: error.overflow } : {};
732
+ this._ended = reason === "done" ? null : { reason, ...(error ? { error: error.message } : {}), ...overflow, at: Date.now() };
710
733
  await this.saveSession();
711
734
  const result = {
712
735
  runId,
@@ -790,26 +813,62 @@ export class Agent {
790
813
  * all of them would fit in `keepRecentTokens`.
791
814
  */
792
815
  compact(focus) {
793
- if (this.current)
794
- return Promise.reject(new Error("cannot compact while a run is active"));
795
- // Runs like a run: messages sent meanwhile queue behind it instead of being lost when the history is replaced.
796
- const controller = new AbortController();
797
- const work = this.chain.then(async () => {
798
- await this.loaded;
816
+ return this.exclusive("compact", async (signal) => {
799
817
  const window = await this.contextTokens();
800
- let settings = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
801
- // Asked for, so it does something: everything before the latest turn may be summarised.
802
- const h = this.history;
803
- let last = h.length - 1;
804
- while (last > 0 && !(h[last].role === "user" && summaryOf(h[last]) === null))
805
- last--;
806
- const latestTurn = last > 0 ? h.slice(last).reduce((n, m) => n + estimateTokens([m]), 0) : Math.floor(estimateTokens(h) / 2);
807
- settings = { ...settings, keepRecentTokens: Math.min(settings.keepRecentTokens, latestTurn) };
808
- const done = await this.compactWith(settings, undefined, controller.signal, focus);
818
+ const settings = this.squeezed(resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {}));
819
+ const done = await this.compactWith(settings, undefined, signal, focus);
809
820
  if (done)
810
821
  await this.saveSession();
811
822
  return done;
812
823
  });
824
+ }
825
+ /**
826
+ * A summary of the conversation that stays out of it, to carry on in a new
827
+ * one (`seed`): everything but `leaveOut`, usually the request to send again.
828
+ * Null when there is nothing to summarise or the summary could not be written.
829
+ */
830
+ summarize(leaveOut) {
831
+ return this.exclusive("summarize", async (signal) => {
832
+ const rest = this.history.filter((m) => m !== leaveOut);
833
+ const first = rest[0] ? summaryOf(rest[0]) : null;
834
+ const toSummarize = first === null ? rest : rest.slice(1);
835
+ if (!toSummarize.length)
836
+ return first;
837
+ const window = await this.contextTokens();
838
+ const settings = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
839
+ this.emit("compaction_start", {});
840
+ try {
841
+ return await this.writeSummary({ toSummarize, previousSummary: first ?? undefined, kept: [] }, settings, undefined, signal);
842
+ }
843
+ catch (err) {
844
+ if (signal.aborted)
845
+ throw err;
846
+ console.warn("[agent] summary failed:", err);
847
+ return null;
848
+ }
849
+ });
850
+ }
851
+ /** Starts an empty conversation from the summary of another (`summarize`). */
852
+ async seed(summary) {
853
+ await this.loaded;
854
+ if (this.current)
855
+ throw new Error("cannot seed while a run is active");
856
+ if (this.history.length)
857
+ throw new Error("seed needs an empty conversation");
858
+ this.history = [summaryMessage(summary)];
859
+ this.committed = 1;
860
+ this._ended = null;
861
+ await this.saveSession();
862
+ }
863
+ /** Runs like a run: messages sent meanwhile queue behind it instead of being lost when the history is replaced. */
864
+ exclusive(what, job) {
865
+ if (this.current)
866
+ return Promise.reject(new Error(`cannot ${what} while a run is active`));
867
+ const controller = new AbortController();
868
+ const work = this.chain.then(async () => {
869
+ await this.loaded;
870
+ return job(controller.signal);
871
+ });
813
872
  const promise = work.then(() => ({ ...abortedResult(), reason: "done" }), () => abortedResult());
814
873
  this.current = { controller, promise };
815
874
  this.chain = promise;
@@ -820,6 +879,95 @@ export class Agent {
820
879
  });
821
880
  return work;
822
881
  }
882
+ /** Settings under which everything before the latest turn may be summarised, even when all of it would fit. */
883
+ squeezed(settings) {
884
+ const h = this.history;
885
+ let last = h.length - 1;
886
+ while (last > 0 && !(h[last].role === "user" && summaryOf(h[last]) === null))
887
+ last--;
888
+ const latestTurn = last > 0 ? h.slice(last).reduce((n, m) => n + estimateTokens([m]), 0) : Math.floor(estimateTokens(h) / 2);
889
+ return { ...settings, keepRecentTokens: Math.min(settings.keepRecentTokens, latestTurn) };
890
+ }
891
+ /**
892
+ * The model refused the request as too large: make it smaller. Round 0
893
+ * summarises what is older than the latest turn and trims to 70% of the
894
+ * window (the estimate may run low); round 1 trims to 40%, big results of the
895
+ * latest turn included. True when the request did get smaller.
896
+ */
897
+ async squeeze(window, round, settings, fixed, runId, signal) {
898
+ const before = estimateTokens(this.history, fixed);
899
+ if (round === 0 && this.opts.compaction !== false)
900
+ await this.compactWith(this.squeezed(settings), runId, signal);
901
+ const pinned = this.history.length && summaryOf(this.history[0]) !== null ? [this.history[0]] : [];
902
+ const rest = this.history.slice(pinned.length);
903
+ const budget = Math.floor(window * (round === 0 ? 0.7 : 0.4)) - estimateTokens(pinned);
904
+ const fit = fitBudget(rest, { budget, keepTurns: 1, system: fixed, keepResults: round === 0 ? 3 : 0 });
905
+ if (fit.droppedTurns || fit.elidedResults) {
906
+ this.history = [...pinned, ...fit.messages];
907
+ this.droppedTurns += fit.droppedTurns;
908
+ this.committed = Math.min(this.committed, this.history.length);
909
+ this.emit("compaction", { runId, summary: false, tokensBefore: before, tokensAfter: estimateTokens(this.history, fixed), droppedTurns: fit.droppedTurns, elidedResults: fit.elidedResults });
910
+ }
911
+ return estimateTokens(this.history, fixed) < before;
912
+ }
913
+ /** What takes up the room in a request that cannot be made smaller. */
914
+ overflowCause(window, fixed) {
915
+ const tools = this.tools.length ? estimateTokens([], JSON.stringify(this.tools.map((t) => toChatTool(t)))) : 0;
916
+ const latest = [...this.history].reverse().find((m) => m.role === "user" && summaryOf(m) === null);
917
+ const asked = latest ? estimateTokens([latest]) : 0;
918
+ const others = estimateTokens(this.history) - asked;
919
+ const biggest = Math.max(tools, asked, others);
920
+ if (biggest * 2 < window)
921
+ return "model";
922
+ if (biggest === asked) {
923
+ const files = Array.isArray(latest.content) ? latest.content.length > 1 : /(^|\n)\[attachments\]/.test(String(latest.content ?? ""));
924
+ return files ? "attachments" : "message";
925
+ }
926
+ return biggest === tools ? "tools" : "history";
927
+ }
928
+ /** The summary of a cut: the host's own summariser, or the model, piece by piece. */
929
+ async writeSummary(plan, settings, runId, signal) {
930
+ if (typeof this.opts.compaction === "function")
931
+ return this.opts.compaction(plan, this);
932
+ const limits = await this.limits();
933
+ // pi: the summary may use most of the reserve, never the model's whole output limit.
934
+ const maxTokens = Math.min(limits.output, Math.max(1024, Math.floor(settings.reserveTokens * 0.8)));
935
+ // What one request can carry (3 characters a token, room for the prompt); a longer history is summarised piece by piece.
936
+ const room = Math.max(6000, (limits.input - maxTokens - 1500) * 3);
937
+ let previous = plan.previousSummary;
938
+ for (const piece of splitForSummary(serializeConversation(plan.toSummarize), room)) {
939
+ const params = { model: this.opts.model ?? "", messages: summarizationMessages(piece, previous, plan.focus), max_tokens: maxTokens };
940
+ if (!params.model)
941
+ delete params.model;
942
+ const tag = { runId: runId ?? "", turn: this.turnNow, purpose: "compaction" };
943
+ this.emit("request", { ...tag, params });
944
+ // A listener may have stopped the run on seeing this request (a call limit): then it never goes out.
945
+ signal.throwIfAborted();
946
+ const asked = Date.now();
947
+ let res;
948
+ try {
949
+ res = this.provider.complete
950
+ ? await this.provider.complete(params, { signal })
951
+ : await collectCompletion((p, init) => this.provider.stream(p, init), params, { signal }).then((c) => ({ choices: [{ message: { ...c.message, content: typeof c.message.content === "string" ? c.message.content : null }, finish_reason: c.finishReason }], usage: c.usage }));
952
+ }
953
+ catch (err) {
954
+ this.emit("response", { ...tag, durationMs: Date.now() - asked, error: err instanceof Error ? err.message : String(err) });
955
+ throw err;
956
+ }
957
+ if (res.usage)
958
+ this.addUsage(res.usage);
959
+ const choice = res.choices[0];
960
+ this.emit("response", { ...tag, durationMs: Date.now() - asked, finishReason: choice?.finish_reason ?? undefined, usage: res.usage ?? undefined, message: choice?.message });
961
+ if (!choice || choice.finish_reason === "length")
962
+ throw new Error("the summary is incomplete");
963
+ if (choice.message.tool_calls?.length)
964
+ throw new Error("the summariser attempted to call a tool");
965
+ previous = (choice.message.content ?? "").trim();
966
+ if (!previous)
967
+ throw new Error("empty summary");
968
+ }
969
+ return previous;
970
+ }
823
971
  async compactWith(settings, runId, signal, focus) {
824
972
  const plan = planCut(this.history, settings.keepRecentTokens);
825
973
  if (!plan)
@@ -830,49 +978,7 @@ export class Agent {
830
978
  const tokensBefore = estimateTokens(this.history);
831
979
  let summary;
832
980
  try {
833
- if (typeof this.opts.compaction === "function") {
834
- summary = await this.opts.compaction(plan, this);
835
- }
836
- else {
837
- const limits = await this.limits();
838
- // pi: the summary may use most of the reserve, never the model's whole output limit.
839
- const maxTokens = Math.min(limits.output, Math.max(1024, Math.floor(settings.reserveTokens * 0.8)));
840
- // What one request can carry (3 characters a token, room for the prompt); a longer history is summarised piece by piece.
841
- const room = Math.max(6000, (limits.input - maxTokens - 1500) * 3);
842
- let previous = plan.previousSummary;
843
- for (const piece of splitForSummary(serializeConversation(plan.toSummarize), room)) {
844
- const params = { model: this.opts.model ?? "", messages: summarizationMessages(piece, previous, plan.focus), max_tokens: maxTokens };
845
- if (!params.model)
846
- delete params.model;
847
- const tag = { runId: runId ?? "", turn: this.turnNow, purpose: "compaction" };
848
- this.emit("request", { ...tag, params });
849
- // A listener may have stopped the run on seeing this request (a call limit): then it never goes out.
850
- signal.throwIfAborted();
851
- const asked = Date.now();
852
- let res;
853
- try {
854
- res = this.provider.complete
855
- ? await this.provider.complete(params, { signal })
856
- : await collectCompletion((p, init) => this.provider.stream(p, init), params, { signal }).then((c) => ({ choices: [{ message: { ...c.message, content: typeof c.message.content === "string" ? c.message.content : null }, finish_reason: c.finishReason }], usage: c.usage }));
857
- }
858
- catch (err) {
859
- this.emit("response", { ...tag, durationMs: Date.now() - asked, error: err instanceof Error ? err.message : String(err) });
860
- throw err;
861
- }
862
- if (res.usage)
863
- this.addUsage(res.usage);
864
- const choice = res.choices[0];
865
- this.emit("response", { ...tag, durationMs: Date.now() - asked, finishReason: choice?.finish_reason ?? undefined, usage: res.usage ?? undefined, message: choice?.message });
866
- if (!choice || choice.finish_reason === "length")
867
- throw new Error("the summary is incomplete");
868
- if (choice.message.tool_calls?.length)
869
- throw new Error("the summariser attempted to call a tool");
870
- previous = (choice.message.content ?? "").trim();
871
- if (!previous)
872
- throw new Error("empty summary");
873
- }
874
- summary = previous;
875
- }
981
+ summary = await this.writeSummary(plan, settings, runId, signal);
876
982
  }
877
983
  catch (err) {
878
984
  if (signal.aborted)