clanka 0.22.2 → 0.22.4

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/bin/cli.mjs CHANGED
@@ -10829,6 +10829,7 @@ var AiError = class extends Error$2("effect/ai/AiError/AiError")({
10829
10829
  return `${this.module}.${this.method}: ${this.reason.message}`;
10830
10830
  }
10831
10831
  };
10832
+ const isAiError = (u) => hasProperty(u, TypeId$8);
10832
10833
  const isAiErrorReason = (u) => hasProperty(u, ReasonTypeId);
10833
10834
  const make$18 = (params) => new AiError(params);
10834
10835
  const reasonFromHttpStatus = (params) => {
@@ -20322,6 +20323,7 @@ const split = (prompt, keepRecentTokens) => {
20322
20323
  kept: messages.slice(cut)
20323
20324
  });
20324
20325
  };
20326
+ const sameSummarizerInput = (self, that) => getOrUndefined(self.previousSummary) === getOrUndefined(that.previousSummary) && self.toSummarize.length === that.toSummarize.length && self.toSummarize.every((message, i) => message === that.toSummarize[i]);
20325
20327
  const trimKept = (kept, keepRecentTokens) => {
20326
20328
  const sizes = kept.map(estimateMessageTokens);
20327
20329
  let total = sizes.reduce((n, size) => n + size, 0);
@@ -20443,7 +20445,10 @@ const compact = fnUntraced(function* (options) {
20443
20445
  return yield* (yield* SummarizerTransform)(ai.streamText({ prompt: summarizerPrompt({
20444
20446
  previousSummary,
20445
20447
  messages: toSummarize
20446
- }) }).pipe(runFold(() => "", (text, part) => part.type === "text-delta" ? text + part.delta : text)));
20448
+ }) }).pipe(runFold(() => "", (text, part) => {
20449
+ options.onActivity?.();
20450
+ return part.type === "text-delta" ? text + part.delta : text;
20451
+ })));
20447
20452
  });
20448
20453
  const summarizerModel = yield* serviceOption(SummarizerModel);
20449
20454
  const summary = (yield* match$2(summarizerModel, {
@@ -20467,17 +20472,6 @@ const compact = fnUntraced(function* (options) {
20467
20472
  tokensAfter: estimateTokens(rewritten)
20468
20473
  });
20469
20474
  });
20470
- const compactIfNeeded = fnUntraced(function* (options) {
20471
- const config = yield* CompactionConfig;
20472
- if (!shouldCompact({
20473
- ...options,
20474
- config
20475
- })) return none();
20476
- return yield* compact({
20477
- ...options,
20478
- reason: "threshold"
20479
- }).pipe(catch_((error) => logWarning("Compaction failed, continuing with the uncompacted prompt", error).pipe(as(none()))));
20480
- });
20481
20475
  // src/AgentOutput.ts
20482
20476
  var AgentStart = class extends TaggedClass$2()("AgentStart", {
20483
20477
  id: Number$2,
@@ -20620,6 +20614,7 @@ const makeWith$1 = fnUntraced(function* (options) {
20620
20614
  let currentOutputAgent = null;
20621
20615
  const history = make$46(empty$1);
20622
20616
  const environment = make$46(capabilities.environment);
20617
+ const backgroundCompactions = new WeakMap();
20623
20618
  const spawn = fnUntraced(function* (opts) {
20624
20619
  const agentId = opts.agentId;
20625
20620
  const ai = yield* LanguageModel;
@@ -20628,6 +20623,8 @@ const makeWith$1 = fnUntraced(function* (options) {
20628
20623
  const conversationMode = yield* ConversationMode;
20629
20624
  const turnTimeout = yield* TurnTimeout;
20630
20625
  const maxRetries = yield* MaxRetries;
20626
+ const compactionConfig = yield* CompactionConfig;
20627
+ const ownSummarizer = isSome(yield* serviceOption(SummarizerModel));
20631
20628
  let finalSummary = none();
20632
20629
  let lastContextTokens = void 0;
20633
20630
  let sendImages = modelConfig.supportsImages !== false;
@@ -20681,7 +20678,6 @@ const makeWith$1 = fnUntraced(function* (options) {
20681
20678
  agentsMd: getOrElse(agentsMd, () => "")
20682
20679
  });
20683
20680
  if (typeof opts.system === "string") system += `\n${opts.system}\n`;
20684
- console.log("system:", system);
20685
20681
  function maybeSend(options) {
20686
20682
  if (!opts.display) {
20687
20683
  offerUnsafe(output, options.part);
@@ -20942,35 +20938,128 @@ ${prompt}`,
20942
20938
  part: new EnvironmentUpdated({ update: update.update.value })
20943
20939
  });
20944
20940
  };
20941
+ const endCompaction = (reason, rewrite) => {
20942
+ const tokensBefore = estimateTokens(prompt.current);
20943
+ let tokensAfter = tokensBefore;
20944
+ if (isSome(rewrite)) {
20945
+ replaceHistory(fromMessages(rewrite.value.prompt.content.filter((message) => !isEnvironmentUpdate(message))));
20946
+ tokensAfter = estimateTokens(rewrite.value.prompt);
20947
+ }
20948
+ maybeSend({
20949
+ agentId,
20950
+ part: new CompactionEnded({
20951
+ reason,
20952
+ tokensBefore,
20953
+ tokensAfter
20954
+ })
20955
+ });
20956
+ if (isSome(rewrite)) applyEnvironmentUpdate(rewrite.value.refresh);
20957
+ };
20945
20958
  const compactWithEvents = (reason, compaction) => suspend(() => {
20946
20959
  compactionStarted = false;
20947
20960
  return compaction;
20948
20961
  }).pipe(flatMap$1(match$2({
20949
20962
  onNone: () => succeedNone,
20950
20963
  onSome: (result) => map$5(renderEnvironment({ reset: true }), (refresh) => some({
20951
- ...result,
20964
+ prompt: result.prompt,
20952
20965
  refresh
20953
20966
  }))
20954
20967
  })), onExit((exit) => sync(() => {
20955
20968
  if (!compactionStarted) return;
20956
- const result = isSuccess(exit) ? exit.value : none();
20957
- let tokensBefore;
20958
- let tokensAfter;
20959
- if (isSome(result)) {
20960
- replaceHistory(fromMessages(result.value.prompt.content.filter((message) => !isEnvironmentUpdate(message))));
20961
- tokensBefore = result.value.tokensBefore;
20962
- tokensAfter = result.value.tokensAfter;
20963
- } else tokensBefore = tokensAfter = estimateTokens(prompt.current);
20969
+ endCompaction(reason, isSuccess(exit) ? exit.value : none());
20970
+ })));
20971
+ const withIdleTimeout = (run) => suspend(() => {
20972
+ let expires = clock.currentTimeMillisUnsafe() + turnTimeoutMs;
20973
+ const onActivity = () => {
20974
+ expires = clock.currentTimeMillisUnsafe() + turnTimeoutMs;
20975
+ };
20976
+ const timeout = gen(function* () {
20977
+ while (true) {
20978
+ const remaining = expires - clock.currentTimeMillisUnsafe();
20979
+ if (remaining <= 0) return yield* new TimeoutError(`The summarizer sent nothing for ${format$1(turnTimeout)}`);
20980
+ yield* sleep(remaining);
20981
+ }
20982
+ });
20983
+ return raceFirst(run(onActivity), timeout);
20984
+ });
20985
+ const state = backgroundCompactions.get(prompt) ?? {
20986
+ running: void 0,
20987
+ failed: void 0,
20988
+ failures: 0,
20989
+ calls: 0
20990
+ };
20991
+ backgroundCompactions.set(prompt, state);
20992
+ const startCompaction = suspend(() => {
20993
+ state.calls++;
20994
+ if (state.running !== void 0 || !shouldCompact({
20995
+ prompt: prompt.current,
20996
+ contextTokens: lastContextTokens,
20997
+ config: compactionConfig
20998
+ })) return void_;
20999
+ const snapshot = prompt.current;
21000
+ const split$1 = split(snapshot, compactionConfig.keepRecentTokens);
21001
+ if (isNone(split$1)) return void_;
21002
+ const { failed } = state;
21003
+ if (failed !== void 0 && state.calls < failed.retryAt && sameSummarizerInput(failed.split, split$1.value)) return void_;
20964
21004
  maybeSend({
20965
21005
  agentId,
20966
- part: new CompactionEnded({
20967
- reason,
20968
- tokensBefore,
20969
- tokensAfter
20970
- })
21006
+ part: new CompactionStarted({ reason: "threshold" })
20971
21007
  });
20972
- if (isSome(result)) applyEnvironmentUpdate(result.value.refresh);
20973
- })));
21008
+ return withIdleTimeout((onActivity) => compact({
21009
+ prompt: snapshot,
21010
+ reason: "threshold",
21011
+ onActivity
21012
+ })).pipe(forkIn(ownSummarizer ? agentScope : runScope, { startImmediately: true }), map$5((fiber) => {
21013
+ state.running = {
21014
+ snapshot,
21015
+ split: split$1.value,
21016
+ outlivesRun: ownSummarizer,
21017
+ fiber
21018
+ };
21019
+ }));
21020
+ });
21021
+ const settleCompaction = suspend(() => {
21022
+ const running = state.running;
21023
+ const exit = running?.fiber.pollUnsafe();
21024
+ if (running === void 0 || exit === void 0) return succeed$1("unchanged");
21025
+ state.running = void 0;
21026
+ if (isFailure(exit)) {
21027
+ if (hasInterruptsOnly(exit.cause)) {
21028
+ endCompaction("threshold", none());
21029
+ return succeed$1("unchanged");
21030
+ }
21031
+ state.failures++;
21032
+ state.failed = {
21033
+ split: running.split,
21034
+ retryAt: state.calls + 4 * 2 ** (state.failures - 1)
21035
+ };
21036
+ endCompaction("threshold", none());
21037
+ const error = squash(exit.cause);
21038
+ return as(logWarning("Compaction failed, continuing with the uncompacted prompt", error), isTimeoutError(error) ? "timed-out" : "unchanged");
21039
+ }
21040
+ state.failures = 0;
21041
+ state.failed = void 0;
21042
+ const next = flatMap$2(exit.value, (result) => rebaseCompaction(running.snapshot, prompt.current, result.prompt));
21043
+ if (isNone(next)) {
21044
+ endCompaction("threshold", none());
21045
+ return succeed$1("unchanged");
21046
+ }
21047
+ return map$5(renderEnvironment({ reset: true }), (refresh) => {
21048
+ endCompaction("threshold", some({
21049
+ prompt: next.value,
21050
+ refresh
21051
+ }));
21052
+ return "applied";
21053
+ });
21054
+ });
21055
+ const awaitCompaction = suspend(() => state.running === void 0 ? settleCompaction : andThen(await_(state.running.fiber), settleCompaction));
21056
+ const cancelRunCompaction = suspend(() => {
21057
+ const running = state.running;
21058
+ if (running === void 0 || running.outlivesRun) return void_;
21059
+ state.running = void 0;
21060
+ endCompaction("threshold", none());
21061
+ return interrupt$2(running.fiber);
21062
+ });
20974
21063
  const executeScript = fnUntraced(function* (script) {
20975
21064
  yield* toolLatchAcquire;
20976
21065
  maybeSend({
@@ -21035,6 +21124,8 @@ ${prompt}`,
21035
21124
  yield* gen(function* () {
21036
21125
  while (true) {
21037
21126
  if (isSome(finalSummary)) {
21127
+ yield* settleCompaction;
21128
+ yield* cancelRunCompaction;
21038
21129
  mailbox.emit = void 0;
21039
21130
  yield* fail$7(output, new AgentFinished({ summary: finalSummary.value }));
21040
21131
  return;
@@ -21066,11 +21157,9 @@ ${prompt}`,
21066
21157
  content: taskMessage(task)
21067
21158
  }))));
21068
21159
  }
21069
- yield* compactWithEvents("threshold", compactIfNeeded({
21070
- prompt: prompt.current,
21071
- contextTokens: lastContextTokens,
21072
- onStart: onCompactionStart
21073
- }).pipe(timeout(turnTimeout))).pipe(catchTag("TimeoutError", (error) => logWarning("Compaction timed out, continuing with the uncompacted prompt", error)));
21160
+ yield* settleCompaction;
21161
+ yield* startCompaction;
21162
+ yield* settleCompaction;
21074
21163
  let response = empty$4();
21075
21164
  let hadToolCall = false;
21076
21165
  let finished = false;
@@ -21216,17 +21305,24 @@ ${prompt}`,
21216
21305
  });
21217
21306
  return attempt;
21218
21307
  }));
21219
- yield* attemptWithImageFallback.pipe(catchIf((err) => err._tag === "AiError" && isContextLengthError(err), (err) => gen(function* () {
21308
+ const overflowCompaction = (err, retryOnTimeout) => gen(function* () {
21220
21309
  discardAttempt();
21221
- const compacted = yield* compactWithEvents("overflow", compact({
21310
+ const compacted = yield* compactWithEvents("overflow", withIdleTimeout((onActivity) => compact({
21222
21311
  prompt: prompt.current,
21223
21312
  reason: "overflow",
21224
- onStart: onCompactionStart
21225
- }).pipe(timeout(turnTimeout), retry({
21313
+ onStart: onCompactionStart,
21314
+ onActivity
21315
+ })).pipe(retry({
21226
21316
  while: (error) => error._tag === "TimeoutError",
21227
- times: 1
21317
+ times: retryOnTimeout ? 1 : 0
21228
21318
  }), catchTag("TimeoutError", die)));
21229
21319
  return isSome(compacted) ? yield* attemptWithImageFallback : yield* err;
21320
+ });
21321
+ yield* attemptWithImageFallback.pipe(catchIf(isOverflow, (err) => gen(function* () {
21322
+ discardAttempt();
21323
+ const settled = yield* awaitCompaction;
21324
+ const compact = (err) => overflowCompaction(err, settled !== "timed-out");
21325
+ return settled === "applied" ? yield* attemptWithImageFallback.pipe(catchIf(isOverflow, compact)) : yield* compact(err);
21230
21326
  })));
21231
21327
  appendHistory(fromResponseParts(response));
21232
21328
  if (pendingImages.length > 0) {
@@ -21293,6 +21389,17 @@ ${prompt}`,
21293
21389
  });
21294
21390
  });
21295
21391
  const make$8 = makeWith$1({});
21392
+ const isOverflow = (err) => isAiError(err) && isContextLengthError(err);
21393
+ const rebaseCompaction = (snapshot, current, compacted) => {
21394
+ const before = snapshot.content.filter((message) => message.role !== "system");
21395
+ const now = current.content.filter((message) => message.role !== "system");
21396
+ if (now.length < before.length || before.some((message, i) => message !== now[i])) return none();
21397
+ return some(fromMessages([
21398
+ ...current.content.filter((message) => message.role === "system"),
21399
+ ...compacted.content.filter((message) => message.role !== "system"),
21400
+ ...now.slice(before.length)
21401
+ ]));
21402
+ };
21296
21403
  const makeMailbox = () => ({
21297
21404
  messages: new Set(),
21298
21405
  notify: () => {},
@@ -21952,6 +22059,14 @@ const make$7 = fnUntraced(function* (options) {
21952
22059
  sessionUpdate: "agent_thought_chunk",
21953
22060
  content: textContent(`Retrying after error: ${part.error.message}\n`)
21954
22061
  });
22062
+ case "CompactionStarted": return update(session.id, {
22063
+ sessionUpdate: "agent_thought_chunk",
22064
+ content: textContent(`Compacting context (${part.reason})...\n`)
22065
+ });
22066
+ case "CompactionEnded": return update(session.id, {
22067
+ sessionUpdate: "agent_thought_chunk",
22068
+ content: textContent(part.tokensAfter < part.tokensBefore ? `Context compacted (${part.reason}): ~${part.tokensBefore} tokens to ~${part.tokensAfter}\n` : `Context not compacted (${part.reason}), continuing with ~${part.tokensBefore} tokens\n`)
22069
+ });
21955
22070
  case "SessionRestarted": return update(session.id, {
21956
22071
  sessionUpdate: "agent_thought_chunk",
21957
22072
  content: textContent(`Session restarted (${part.reason}): ${part.contextTokens} context tokens resent, ${part.cacheWrite} cache write\n`)
@@ -28513,7 +28628,7 @@ const transformToolCallParams$1 = fnUntraced(function* (options, toolName, toolP
28513
28628
  return yield* decodeEffect(codec)(toolParams).pipe(flatMap$1((decoded) => encodeUnknownEffect(tool.parametersSchema)(decoded)), orElseSucceed(() => toolParams));
28514
28629
  });
28515
28630
  // package.json
28516
- var version$1 = "0.22.2";
28631
+ var version$1 = "0.22.4";
28517
28632
  // src/ClaudeAgent.ts
28518
28633
  const minimumClaudeCodeVersion = "2.1.248";
28519
28634
  const serverName = "clanka";
@@ -31068,7 +31183,7 @@ const languageModel = (provider, model, effort, openai, fastMode) => {
31068
31183
  const make = (provider, model, effort, openai, fastMode = false, auxiliary) => {
31069
31184
  const fromSpec = (spec) => languageModel(spec.provider, spec.model, spec.effort, openai, fastMode);
31070
31185
  const main = languageModel(provider, model, effort, openai, fastMode);
31071
- return mergeAll(main, layerSubagentModel(auxiliary?.subagent === void 0 ? main : fromSpec(auxiliary.subagent)), auxiliary?.summarizer === void 0 ? empty$7 : layerSummarizerModel(fromSpec(auxiliary.summarizer)));
31186
+ return mergeAll(main, layerSubagentModel(auxiliary?.subagent === void 0 ? main : fromSpec(auxiliary.subagent)), layerSummarizerModel(auxiliary?.summarizer === void 0 ? main : fromSpec(auxiliary.summarizer)));
31072
31187
  };
31073
31188
  const isProvider$1 = is(Provider);
31074
31189
  const parseAcpModelId = (modelId) => {