clanka 0.18.1 → 0.19.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.
package/dist/bin/cli.mjs CHANGED
@@ -11567,6 +11567,18 @@ const subagentsUnavailable = {
11567
11567
  listAgents: succeed$1([])
11568
11568
  };
11569
11569
  var ImageAttacher = class extends Service()("clanka/AgentTools/ImageAttacher") {};
11570
+ const BashJobStatus = Literals$2([
11571
+ "running",
11572
+ "completed",
11573
+ "failed",
11574
+ "stopped"
11575
+ ]);
11576
+ const BashJob = Struct({
11577
+ id: String$7,
11578
+ status: BashJobStatus,
11579
+ exitCode: optional$2(Number$2),
11580
+ output: String$7
11581
+ });
11570
11582
  const defaultBashTimeout = minutes(10);
11571
11583
  const defaultMcpCallTimeout = minutes(10);
11572
11584
  var CommandLimits = class extends Reference("clanka/AgentTools/CommandLimits", { defaultValue: () => ({
@@ -11574,10 +11586,11 @@ var CommandLimits = class extends Reference("clanka/AgentTools/CommandLimits", {
11574
11586
  outputChars: void 0
11575
11587
  }) }) {};
11576
11588
  const makeBashTool = (timeout) => make$17("bash", {
11577
- description: "Run a bash command and return the output",
11589
+ description: "Run a bash command and return the output. With `background: true` it returns straight away with a job id while the command keeps running. A command still running at its timeout is not stopped: it is moved to the background, and the output so far is returned with its job id. Read a job with \"jobOutput\" and stop it with \"stopJob\".",
11578
11590
  parameters: Struct({
11579
11591
  command: String$7,
11580
- timeoutMs: optional$2(Finite).annotate({ documentation: `Timeout in ms (default and max: ${toMillis(timeout)})` })
11592
+ timeoutMs: optional$2(Finite).annotate({ documentation: `How long to wait in ms before moving the command to the background (default and max: ${toMillis(timeout)})` }),
11593
+ background: optional$2(Boolean$4).annotate({ documentation: "Start the command in the background and return its job id without waiting" })
11581
11594
  }).annotate({ identifier: "command" }),
11582
11595
  success: String$7,
11583
11596
  dependencies: [CurrentDirectory]
@@ -11653,7 +11666,17 @@ const AgentTools = make$16(make$17("changeDirectory", {
11653
11666
  parameters: ArraySchema(String$7).annotate({ identifier: "args" }),
11654
11667
  success: String$7,
11655
11668
  dependencies: [CurrentDirectory]
11656
- }), makeBashTool(defaultBashTimeout), make$17("applyPatch", {
11669
+ }), makeBashTool(defaultBashTimeout), make$17("jobOutput", {
11670
+ description: "Return the status and output so far of a background bash job.",
11671
+ parameters: String$7.annotate({ identifier: "id" }),
11672
+ success: BashJob,
11673
+ failure: String$7
11674
+ }), make$17("stopJob", {
11675
+ description: "Stop a background bash job and return its final status and output.",
11676
+ parameters: String$7.annotate({ identifier: "id" }),
11677
+ success: BashJob,
11678
+ failure: String$7
11679
+ }), make$17("applyPatch", {
11657
11680
  description: "Add, update or remove multiple files with a git diff / unified diff / wrapped patch.",
11658
11681
  parameters: String$7.annotate({ identifier: "patch" }),
11659
11682
  success: String$7,
@@ -11711,18 +11734,45 @@ const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(gen(function* () {
11711
11734
  const pathService = yield* Path$3;
11712
11735
  const webSearch = yield* ExaSearch;
11713
11736
  const fetchMarkdown = yield* WebToMarkdown;
11714
- const execute = fn(function* (command, _timeout) {
11737
+ const commandScope = yield* scope;
11738
+ const startCommand = fnUntraced(function* (command) {
11715
11739
  const { outputChars } = yield* CommandLimits;
11716
- const handle = yield* spawner.spawn(command);
11717
- return yield* handle.all.pipe(decodeText, outputChars === void 0 ? mkString : collectBounded(outputChars), flatMap$1(fnUntraced(function* (output) {
11718
- const exitCode = yield* handle.exitCode;
11719
- if (exitCode === 0) return output;
11720
- return yield* die(new Error(`Command failed with exit code ${exitCode}: ${output}`));
11721
- })));
11722
- }, (effect, _command, timeout) => timeout === void 0 ? effect : timeoutOrElse(effect, {
11723
- duration: timeout,
11724
- orElse: () => die(new Error(`Command timed out after ${toMillis(timeout)}ms`))
11725
- }), scoped);
11740
+ const output = makeOutputBuffer(outputChars);
11741
+ return {
11742
+ fiber: yield* spawner.spawn(command).pipe(flatMap$1((handle) => handle.all.pipe(decodeText, runForEach((chunk) => sync(() => output.append(chunk))), andThen(handle.exitCode))), scoped, forkIn(commandScope)),
11743
+ output: output.render
11744
+ };
11745
+ });
11746
+ const jobs = new Map();
11747
+ let nextJobId = 1;
11748
+ const addJob = (running) => {
11749
+ const id = String(nextJobId++);
11750
+ jobs.set(id, running);
11751
+ return id;
11752
+ };
11753
+ const findJob = (id) => {
11754
+ const running = jobs.get(id);
11755
+ return running === void 0 ? fail$1(`No background job with id "${id}"`) : succeed$1(running);
11756
+ };
11757
+ const runCommand = fnUntraced(function* (command, timeout, onTimeout) {
11758
+ const running = yield* startCommand(command);
11759
+ const awaited = await_(running.fiber);
11760
+ const exit = yield* (timeout === void 0 ? asSome(awaited) : timeoutOption(awaited, timeout)).pipe(onInterrupt(() => interrupt$2(running.fiber)));
11761
+ if (isNone(exit)) {
11762
+ const timeoutMs = toMillis(timeout);
11763
+ if (onTimeout === "stop") {
11764
+ yield* interrupt$2(running.fiber);
11765
+ return yield* die(new Error(`Command timed out after ${timeoutMs}ms`));
11766
+ }
11767
+ const id = addJob(running);
11768
+ const output = running.output();
11769
+ return `${output}${output === "" || output.endsWith("\n") ? "" : "\n"}[Still running after ${timeoutMs}ms, so it was moved to the background as job ${id}. ${jobUsage(id)}]`;
11770
+ }
11771
+ const exitCode = yield* exit.value;
11772
+ const output = running.output();
11773
+ if (exitCode === 0) return output;
11774
+ return yield* die(new Error(`Command failed with exit code ${exitCode}: ${output}`));
11775
+ });
11726
11776
  const readImage = fnUntraced(function* (path, extensionType, options) {
11727
11777
  if (options.startLine !== void 0 || options.endLine !== void 0) return yield* die(new Error(`startLine / endLine are not supported for images: ${path}`));
11728
11778
  const bytes = yield* readBoundedFile(fs, path).pipe(catchReason("PlatformError", "NotFound", () => succeed$1(null)), orDie);
@@ -11839,8 +11889,24 @@ const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(gen(function* () {
11839
11889
  cwd,
11840
11890
  stdin: "ignore"
11841
11891
  });
11842
- return yield* execute(cmd, millis(timeoutMs));
11892
+ if (options.background === true) {
11893
+ const id = addJob(yield* startCommand(cmd));
11894
+ return `Started background job ${id}. ${jobUsage(id)}`;
11895
+ }
11896
+ return yield* runCommand(cmd, millis(timeoutMs), "background");
11843
11897
  }, orDie),
11898
+ jobOutput: fn("AgentTools.jobOutput")(function* (input) {
11899
+ const id = yield* decodeJobOutput(input);
11900
+ yield* logInfo(`Calling "jobOutput"`).pipe(annotateLogs({ id }));
11901
+ return jobInfo(id, yield* findJob(id));
11902
+ }),
11903
+ stopJob: fn("AgentTools.stopJob")(function* (input) {
11904
+ const id = yield* decodeStopJob(input);
11905
+ yield* logInfo(`Calling "stopJob"`).pipe(annotateLogs({ id }));
11906
+ const running = yield* findJob(id);
11907
+ yield* interrupt$2(running.fiber);
11908
+ return jobInfo(id, running);
11909
+ }),
11844
11910
  gh: fn("AgentTools.gh")(function* (args) {
11845
11911
  yield* logInfo(`Calling "gh"`).pipe(annotateLogs({ args }));
11846
11912
  const cwd = yield* CurrentDirectory;
@@ -11849,7 +11915,7 @@ const AgentToolHandlersNoDeps = AgentToolsWithSearch.toLayer(gen(function* () {
11849
11915
  stdin: "ignore"
11850
11916
  });
11851
11917
  const { timeout } = yield* CommandLimits;
11852
- return yield* execute(cmd, timeout);
11918
+ return yield* runCommand(cmd, timeout, "stop");
11853
11919
  }, orDie),
11854
11920
  webSearch: fn("AgentTools.webSearch")(function* (options) {
11855
11921
  yield* logInfo(`Calling "webSearch"`).pipe(annotateLogs(options));
@@ -11994,26 +12060,57 @@ const decodeDelegate = decodeParams$1(AgentTools.tools.delegate.parametersSchema
11994
12060
  const decodeWaitAgents = decodeParams$1(AgentTools.tools.waitAgents.parametersSchema, "waitAgents takes an optional array of agent ids, for example: waitAgents([\"3\", \"4\"]).");
11995
12061
  const decodeMessageAgent = decodeParams$1(AgentTools.tools.messageAgent.parametersSchema, "messageAgent requires an options object, for example: messageAgent({ id: \"3\", message: \"...\" }).");
11996
12062
  const decodeStopAgent = decodeParams$1(AgentTools.tools.stopAgent.parametersSchema, "stopAgent requires an agent id, for example: stopAgent(\"3\").");
11997
- const collectBounded = (maxChars) => (stream) => {
11998
- const headChars = Math.floor(maxChars / 2);
11999
- const tailChars = maxChars - headChars;
12063
+ const decodeJobOutput = decodeParams$1(AgentTools.tools.jobOutput.parametersSchema, "jobOutput requires a job id, for example: jobOutput(\"1\").");
12064
+ const decodeStopJob = decodeParams$1(AgentTools.tools.stopJob.parametersSchema, "stopJob requires a job id, for example: stopJob(\"1\").");
12065
+ const jobUsage = (id) => `Use jobOutput("${id}") for its status and output, or stopJob("${id}") to stop it.`;
12066
+ const jobInfo = (id, running) => {
12067
+ const exit = running.fiber.pollUnsafe();
12068
+ const output = running.output();
12069
+ if (exit === void 0) return {
12070
+ id,
12071
+ status: "running",
12072
+ output
12073
+ };
12074
+ if (isSuccess(exit)) return {
12075
+ id,
12076
+ status: exit.value === 0 ? "completed" : "failed",
12077
+ exitCode: exit.value,
12078
+ output
12079
+ };
12080
+ if (hasInterruptsOnly(exit.cause)) return {
12081
+ id,
12082
+ status: "stopped",
12083
+ output
12084
+ };
12085
+ return {
12086
+ id,
12087
+ status: "failed",
12088
+ output: `${output}${output === "" ? "" : "\n"}${pretty(exit.cause)}`
12089
+ };
12090
+ };
12091
+ const makeOutputBuffer = (maxChars) => {
12092
+ const headChars = maxChars === void 0 ? Number.POSITIVE_INFINITY : Math.floor(maxChars / 2);
12093
+ const tailChars = maxChars === void 0 ? 0 : maxChars - headChars;
12000
12094
  let head = "";
12001
12095
  let tail = "";
12002
12096
  let total = 0;
12003
- return stream.pipe(runForEach((chunk) => sync(() => {
12004
- total += chunk.length;
12005
- let rest = chunk;
12006
- if (head.length < headChars) {
12007
- const take = headChars - head.length;
12008
- head += rest.slice(0, take);
12009
- rest = rest.slice(take);
12010
- }
12011
- if (rest.length > 0 && tailChars > 0) tail = (tail + rest).slice(-tailChars);
12012
- })), map$5(() => {
12013
- const omitted = total - head.length - tail.length;
12014
- if (omitted <= 0) return head + tail;
12015
- return `${head}\n\n[... ${omitted} of ${total} chars omitted from the middle of the output ...]\n\n${tail}`;
12016
- }));
12097
+ return {
12098
+ append(chunk) {
12099
+ total += chunk.length;
12100
+ let rest = chunk;
12101
+ if (head.length < headChars) {
12102
+ const take = headChars - head.length;
12103
+ head += rest.slice(0, take);
12104
+ rest = rest.slice(take);
12105
+ }
12106
+ if (rest.length > 0 && tailChars > 0) tail = (tail + rest).slice(-tailChars);
12107
+ },
12108
+ render() {
12109
+ const omitted = total - head.length - tail.length;
12110
+ if (omitted <= 0) return head + tail;
12111
+ return `${head}\n\n[... ${omitted} of ${total} chars omitted from the middle of the output ...]\n\n${tail}`;
12112
+ }
12113
+ };
12017
12114
  };
12018
12115
  var ApplyPatchError = class extends TaggedClass$1("ApplyPatchError") {};
12019
12116
  // src/TypeBuilder.ts
@@ -14243,14 +14340,11 @@ const makeRpc = gen(function* () {
14243
14340
  environment,
14244
14341
  reset: options?.reset ?? false
14245
14342
  }).pipe(orDie),
14246
- executeUnsafe({ environment, ...options }) {
14247
- return encodeRpcParams(options.tool, options.params).pipe(flatMap$1((params) => client.executeUnsafe(environment === void 0 ? {
14248
- ...options,
14249
- params
14250
- } : {
14251
- ...options,
14252
- params,
14253
- environment
14343
+ executeUnsafe({ tool, params, environment }) {
14344
+ return encodeRpcParams(tool, params).pipe(flatMap$1((json) => client.executeUnsafe({
14345
+ tool,
14346
+ ...json === void 0 ? void 0 : { params: json },
14347
+ ...environment === void 0 ? void 0 : { environment }
14254
14348
  })), orDie);
14255
14349
  }
14256
14350
  });
@@ -14314,7 +14408,7 @@ var Rpcs = class extends make$12(make$14("capabilities", { success: Capabilities
14314
14408
  }), make$14("executeUnsafe", {
14315
14409
  payload: Struct({
14316
14410
  tool: String$7,
14317
- params: Json,
14411
+ params: optionalKey(Json),
14318
14412
  environment: optionalKey(ExecutionEnvironment)
14319
14413
  }),
14320
14414
  success: Json
@@ -14326,7 +14420,20 @@ const RpcWriteFileParams = Struct({
14326
14420
  encode: (base64) => ({ base64 })
14327
14421
  })))])
14328
14422
  });
14329
- const encodeRpcParams = (tool, params) => tool === "writeFile" ? encodeUnknownEffect(RpcWriteFileParams)(params) : succeed$1(params);
14423
+ const isPlainObject = (value) => {
14424
+ if (!isObject$1(value)) return false;
14425
+ const proto = Object.getPrototypeOf(value);
14426
+ return proto === Object.prototype || proto === null;
14427
+ };
14428
+ const dropUndefined = (value) => {
14429
+ if (Array.isArray(value)) return value.map((item) => dropUndefined(item) ?? null);
14430
+ if (!isPlainObject(value)) return value;
14431
+ return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== void 0).map(([key, field]) => [key, dropUndefined(field)]));
14432
+ };
14433
+ const encodeRpcParams = (tool, params) => {
14434
+ const json = dropUndefined(params);
14435
+ return tool === "writeFile" ? encodeUnknownEffect(RpcWriteFileParams)(json) : succeed$1(json);
14436
+ };
14330
14437
  const handleRequest = (opts, request) => {
14331
14438
  switch (request._tag) {
14332
14439
  case "TaskComplete": return opts.onTaskComplete(request.summary);
@@ -14362,6 +14469,10 @@ const excludedToolNames = (excludeTools) => {
14362
14469
  "stopAgent",
14363
14470
  "listAgents"
14364
14471
  ]) names.add(name);
14472
+ if (names.has("bash")) {
14473
+ names.add("jobOutput");
14474
+ names.add("stopJob");
14475
+ }
14365
14476
  return names;
14366
14477
  };
14367
14478
  const wrapScript = (script) => `async function main() {
@@ -21107,7 +21218,8 @@ const generateSystemTools = (tools, conversationMode) => `YOU ONLY HAVE ONE TOOL
21107
21218
  - Use top level await.${when(tools.offers("search") && tools.offers("rg"), `
21108
21219
  - Prefer using the "search" function over "rg", unless you are targeting specific files or patterns.`)}${when(tools.offers("applyPatch"), `
21109
21220
  - You can add / update / remove multiple files in one go with "applyPatch".${when(tools.offers("writeFile"), ` Prefer it over "writeFile" to update existing files.`)}`)}${when(tools.offers("bash"), `
21110
- - Avoid passing scripts into the "bash" function, and instead write javascript.`)}
21221
+ - Avoid passing scripts into the "bash" function, and instead write javascript.
21222
+ - Pass \`background: true\` to "bash" for commands that keep running, such as dev servers or watchers. A command still running at its timeout is moved to the background instead of being stopped. Use "jobOutput" and "stopJob" with the returned job id.`)}
21111
21223
  - Variables are not shared between executions.
21112
21224
  - Do not use \`require\`, \`import\`, \`process\`, or any other Node.js apis.${when(tools.offers("delegate"), `
21113
21225
  - "delegate" runs a sub-agent and waits for it. Pass \`background: true\` to keep working while it runs: its result is sent to you later as a \`<subagent id="..." status="...">\` message.${when(tools.offers("waitAgents"), ` Use "waitAgents" to wait for the returned id.`)}${when(tools.offers("messageAgent"), ` Use "messageAgent" to send a message to the returned id.`)}${when(tools.offers("stopAgent"), ` Use "stopAgent" to stop the returned id.`)}${when(tools.offers("listAgents"), ` "listAgents" shows the agents you started.`)}`)}${when(!conversationMode, `
@@ -28238,7 +28350,7 @@ const transformToolCallParams$1 = fnUntraced(function* (options, toolName, toolP
28238
28350
  return yield* decodeEffect(codec)(toolParams).pipe(flatMap$1((decoded) => encodeUnknownEffect(tool.parametersSchema)(decoded)), orElseSucceed(() => toolParams));
28239
28351
  });
28240
28352
  // package.json
28241
- var version$1 = "0.18.1";
28353
+ var version$1 = "0.19.0";
28242
28354
  // src/ClaudeAgent.ts
28243
28355
  const minimumClaudeCodeVersion = "2.1.248";
28244
28356
  const serverName = "clanka";