clanka 0.22.1 → 0.22.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/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) => {
@@ -20183,7 +20184,7 @@ const defaultConfig = {
20183
20184
  enabled: true,
20184
20185
  contextWindow: 236e3,
20185
20186
  reserveTokens: 16e3,
20186
- thresholdTokens: 16e4,
20187
+ thresholdTokens: 2e5,
20187
20188
  keepRecentTokens: 2e4
20188
20189
  };
20189
20190
  var CompactionConfig = class CompactionConfig extends Reference("clanka/Compaction/CompactionConfig", { defaultValue: () => defaultConfig }) {
@@ -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;
@@ -20942,35 +20939,128 @@ ${prompt}`,
20942
20939
  part: new EnvironmentUpdated({ update: update.update.value })
20943
20940
  });
20944
20941
  };
20942
+ const endCompaction = (reason, rewrite) => {
20943
+ const tokensBefore = estimateTokens(prompt.current);
20944
+ let tokensAfter = tokensBefore;
20945
+ if (isSome(rewrite)) {
20946
+ replaceHistory(fromMessages(rewrite.value.prompt.content.filter((message) => !isEnvironmentUpdate(message))));
20947
+ tokensAfter = estimateTokens(rewrite.value.prompt);
20948
+ }
20949
+ maybeSend({
20950
+ agentId,
20951
+ part: new CompactionEnded({
20952
+ reason,
20953
+ tokensBefore,
20954
+ tokensAfter
20955
+ })
20956
+ });
20957
+ if (isSome(rewrite)) applyEnvironmentUpdate(rewrite.value.refresh);
20958
+ };
20945
20959
  const compactWithEvents = (reason, compaction) => suspend(() => {
20946
20960
  compactionStarted = false;
20947
20961
  return compaction;
20948
20962
  }).pipe(flatMap$1(match$2({
20949
20963
  onNone: () => succeedNone,
20950
20964
  onSome: (result) => map$5(renderEnvironment({ reset: true }), (refresh) => some({
20951
- ...result,
20965
+ prompt: result.prompt,
20952
20966
  refresh
20953
20967
  }))
20954
20968
  })), onExit((exit) => sync(() => {
20955
20969
  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);
20970
+ endCompaction(reason, isSuccess(exit) ? exit.value : none());
20971
+ })));
20972
+ const withIdleTimeout = (run) => suspend(() => {
20973
+ let expires = clock.currentTimeMillisUnsafe() + turnTimeoutMs;
20974
+ const onActivity = () => {
20975
+ expires = clock.currentTimeMillisUnsafe() + turnTimeoutMs;
20976
+ };
20977
+ const timeout = gen(function* () {
20978
+ while (true) {
20979
+ const remaining = expires - clock.currentTimeMillisUnsafe();
20980
+ if (remaining <= 0) return yield* new TimeoutError(`The summarizer sent nothing for ${format$1(turnTimeout)}`);
20981
+ yield* sleep(remaining);
20982
+ }
20983
+ });
20984
+ return raceFirst(run(onActivity), timeout);
20985
+ });
20986
+ const state = backgroundCompactions.get(prompt) ?? {
20987
+ running: void 0,
20988
+ failed: void 0,
20989
+ failures: 0,
20990
+ calls: 0
20991
+ };
20992
+ backgroundCompactions.set(prompt, state);
20993
+ const startCompaction = suspend(() => {
20994
+ state.calls++;
20995
+ if (state.running !== void 0 || !shouldCompact({
20996
+ prompt: prompt.current,
20997
+ contextTokens: lastContextTokens,
20998
+ config: compactionConfig
20999
+ })) return void_;
21000
+ const snapshot = prompt.current;
21001
+ const split$1 = split(snapshot, compactionConfig.keepRecentTokens);
21002
+ if (isNone(split$1)) return void_;
21003
+ const { failed } = state;
21004
+ if (failed !== void 0 && state.calls < failed.retryAt && sameSummarizerInput(failed.split, split$1.value)) return void_;
20964
21005
  maybeSend({
20965
21006
  agentId,
20966
- part: new CompactionEnded({
20967
- reason,
20968
- tokensBefore,
20969
- tokensAfter
20970
- })
21007
+ part: new CompactionStarted({ reason: "threshold" })
20971
21008
  });
20972
- if (isSome(result)) applyEnvironmentUpdate(result.value.refresh);
20973
- })));
21009
+ return withIdleTimeout((onActivity) => compact({
21010
+ prompt: snapshot,
21011
+ reason: "threshold",
21012
+ onActivity
21013
+ })).pipe(forkIn(ownSummarizer ? agentScope : runScope, { startImmediately: true }), map$5((fiber) => {
21014
+ state.running = {
21015
+ snapshot,
21016
+ split: split$1.value,
21017
+ outlivesRun: ownSummarizer,
21018
+ fiber
21019
+ };
21020
+ }));
21021
+ });
21022
+ const settleCompaction = suspend(() => {
21023
+ const running = state.running;
21024
+ const exit = running?.fiber.pollUnsafe();
21025
+ if (running === void 0 || exit === void 0) return succeed$1("unchanged");
21026
+ state.running = void 0;
21027
+ if (isFailure(exit)) {
21028
+ if (hasInterruptsOnly(exit.cause)) {
21029
+ endCompaction("threshold", none());
21030
+ return succeed$1("unchanged");
21031
+ }
21032
+ state.failures++;
21033
+ state.failed = {
21034
+ split: running.split,
21035
+ retryAt: state.calls + 4 * 2 ** (state.failures - 1)
21036
+ };
21037
+ endCompaction("threshold", none());
21038
+ const error = squash(exit.cause);
21039
+ return as(logWarning("Compaction failed, continuing with the uncompacted prompt", error), isTimeoutError(error) ? "timed-out" : "unchanged");
21040
+ }
21041
+ state.failures = 0;
21042
+ state.failed = void 0;
21043
+ const next = flatMap$2(exit.value, (result) => rebaseCompaction(running.snapshot, prompt.current, result.prompt));
21044
+ if (isNone(next)) {
21045
+ endCompaction("threshold", none());
21046
+ return succeed$1("unchanged");
21047
+ }
21048
+ return map$5(renderEnvironment({ reset: true }), (refresh) => {
21049
+ endCompaction("threshold", some({
21050
+ prompt: next.value,
21051
+ refresh
21052
+ }));
21053
+ return "applied";
21054
+ });
21055
+ });
21056
+ const awaitCompaction = suspend(() => state.running === void 0 ? settleCompaction : andThen(await_(state.running.fiber), settleCompaction));
21057
+ const cancelRunCompaction = suspend(() => {
21058
+ const running = state.running;
21059
+ if (running === void 0 || running.outlivesRun) return void_;
21060
+ state.running = void 0;
21061
+ endCompaction("threshold", none());
21062
+ return interrupt$2(running.fiber);
21063
+ });
20974
21064
  const executeScript = fnUntraced(function* (script) {
20975
21065
  yield* toolLatchAcquire;
20976
21066
  maybeSend({
@@ -21035,6 +21125,8 @@ ${prompt}`,
21035
21125
  yield* gen(function* () {
21036
21126
  while (true) {
21037
21127
  if (isSome(finalSummary)) {
21128
+ yield* settleCompaction;
21129
+ yield* cancelRunCompaction;
21038
21130
  mailbox.emit = void 0;
21039
21131
  yield* fail$7(output, new AgentFinished({ summary: finalSummary.value }));
21040
21132
  return;
@@ -21066,11 +21158,9 @@ ${prompt}`,
21066
21158
  content: taskMessage(task)
21067
21159
  }))));
21068
21160
  }
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)));
21161
+ yield* settleCompaction;
21162
+ yield* startCompaction;
21163
+ yield* settleCompaction;
21074
21164
  let response = empty$4();
21075
21165
  let hadToolCall = false;
21076
21166
  let finished = false;
@@ -21216,17 +21306,24 @@ ${prompt}`,
21216
21306
  });
21217
21307
  return attempt;
21218
21308
  }));
21219
- yield* attemptWithImageFallback.pipe(catchIf((err) => err._tag === "AiError" && isContextLengthError(err), (err) => gen(function* () {
21309
+ const overflowCompaction = (err, retryOnTimeout) => gen(function* () {
21220
21310
  discardAttempt();
21221
- const compacted = yield* compactWithEvents("overflow", compact({
21311
+ const compacted = yield* compactWithEvents("overflow", withIdleTimeout((onActivity) => compact({
21222
21312
  prompt: prompt.current,
21223
21313
  reason: "overflow",
21224
- onStart: onCompactionStart
21225
- }).pipe(timeout(turnTimeout), retry({
21314
+ onStart: onCompactionStart,
21315
+ onActivity
21316
+ })).pipe(retry({
21226
21317
  while: (error) => error._tag === "TimeoutError",
21227
- times: 1
21318
+ times: retryOnTimeout ? 1 : 0
21228
21319
  }), catchTag("TimeoutError", die)));
21229
21320
  return isSome(compacted) ? yield* attemptWithImageFallback : yield* err;
21321
+ });
21322
+ yield* attemptWithImageFallback.pipe(catchIf(isOverflow, (err) => gen(function* () {
21323
+ discardAttempt();
21324
+ const settled = yield* awaitCompaction;
21325
+ const compact = (err) => overflowCompaction(err, settled !== "timed-out");
21326
+ return settled === "applied" ? yield* attemptWithImageFallback.pipe(catchIf(isOverflow, compact)) : yield* compact(err);
21230
21327
  })));
21231
21328
  appendHistory(fromResponseParts(response));
21232
21329
  if (pendingImages.length > 0) {
@@ -21293,6 +21390,17 @@ ${prompt}`,
21293
21390
  });
21294
21391
  });
21295
21392
  const make$8 = makeWith$1({});
21393
+ const isOverflow = (err) => isAiError(err) && isContextLengthError(err);
21394
+ const rebaseCompaction = (snapshot, current, compacted) => {
21395
+ const before = snapshot.content.filter((message) => message.role !== "system");
21396
+ const now = current.content.filter((message) => message.role !== "system");
21397
+ if (now.length < before.length || before.some((message, i) => message !== now[i])) return none();
21398
+ return some(fromMessages([
21399
+ ...current.content.filter((message) => message.role === "system"),
21400
+ ...compacted.content.filter((message) => message.role !== "system"),
21401
+ ...now.slice(before.length)
21402
+ ]));
21403
+ };
21296
21404
  const makeMailbox = () => ({
21297
21405
  messages: new Set(),
21298
21406
  notify: () => {},
@@ -21952,6 +22060,14 @@ const make$7 = fnUntraced(function* (options) {
21952
22060
  sessionUpdate: "agent_thought_chunk",
21953
22061
  content: textContent(`Retrying after error: ${part.error.message}\n`)
21954
22062
  });
22063
+ case "CompactionStarted": return update(session.id, {
22064
+ sessionUpdate: "agent_thought_chunk",
22065
+ content: textContent(`Compacting context (${part.reason})...\n`)
22066
+ });
22067
+ case "CompactionEnded": return update(session.id, {
22068
+ sessionUpdate: "agent_thought_chunk",
22069
+ 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`)
22070
+ });
21955
22071
  case "SessionRestarted": return update(session.id, {
21956
22072
  sessionUpdate: "agent_thought_chunk",
21957
22073
  content: textContent(`Session restarted (${part.reason}): ${part.contextTokens} context tokens resent, ${part.cacheWrite} cache write\n`)
@@ -28513,7 +28629,7 @@ const transformToolCallParams$1 = fnUntraced(function* (options, toolName, toolP
28513
28629
  return yield* decodeEffect(codec)(toolParams).pipe(flatMap$1((decoded) => encodeUnknownEffect(tool.parametersSchema)(decoded)), orElseSucceed(() => toolParams));
28514
28630
  });
28515
28631
  // package.json
28516
- var version$1 = "0.22.1";
28632
+ var version$1 = "0.22.3";
28517
28633
  // src/ClaudeAgent.ts
28518
28634
  const minimumClaudeCodeVersion = "2.1.248";
28519
28635
  const serverName = "clanka";
@@ -31068,7 +31184,7 @@ const languageModel = (provider, model, effort, openai, fastMode) => {
31068
31184
  const make = (provider, model, effort, openai, fastMode = false, auxiliary) => {
31069
31185
  const fromSpec = (spec) => languageModel(spec.provider, spec.model, spec.effort, openai, fastMode);
31070
31186
  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)));
31187
+ return mergeAll(main, layerSubagentModel(auxiliary?.subagent === void 0 ? main : fromSpec(auxiliary.subagent)), layerSummarizerModel(auxiliary?.summarizer === void 0 ? main : fromSpec(auxiliary.summarizer)));
31072
31188
  };
31073
31189
  const isProvider$1 = is(Provider);
31074
31190
  const parseAcpModelId = (modelId) => {