@bastani/atomic 0.9.20-alpha.10 → 0.9.20-alpha.11

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/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.9.20-alpha.11] - 2026-09-24
6
+
7
+ ### Changed
8
+
9
+ - The agent no longer treats missing, sparse, or mostly inline workflow history as a reason to run every task inline. It judges from the task itself whether a workflow would help, then refines that choice with comparable execution history and your stated or recorded preferences.
10
+
11
+ ### Fixed
12
+
13
+ - The `curl | sh` and `irm | iex` installers can install older releases again. They no longer run `--internal-validate-postgres-runtime` or the bundled PostgreSQL `--version` checks before promotion. Installing a release built before that option existed, or one without a bundled PostgreSQL runtime, could fail before promotion. The installers still verify the SHA256 checksum and run the staged `atomic --version`.
14
+ - Durable workflows work again on Ubuntu and Debian with the default umask 002. Atomic had refused its own group-writable `~/.atomic` as an ancestor of the PostgreSQL runtime cache and ran workflows in memory, so runs couldn't be resumed after closing Atomic. A group-writable folder is now accepted when its group is your private group: no other account in `/etc/passwd` uses it as its primary group, and `/etc/group` lists no member other than you. World-writable folders and shared groups are still rejected.
15
+
5
16
  ## [0.9.20-alpha.10] - 2026-09-24
6
17
 
7
18
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/intercom",
3
- "version": "0.9.20-alpha.10",
3
+ "version": "0.9.20-alpha.11",
4
4
  "private": true,
5
5
  "description": "Atomic extension providing a private coordination channel between parent and child agent sessions. Fork of: https://github.com/nicobailon/pi-intercom",
6
6
  "contributors": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/mcp",
3
- "version": "0.9.20-alpha.10",
3
+ "version": "0.9.20-alpha.11",
4
4
  "private": true,
5
5
  "description": "Atomic extension that adapts MCP (Model Context Protocol) servers into the coding agent. Fork of: https://github.com/nicobailon/pi-mcp-adapter",
6
6
  "contributors": [
@@ -2,6 +2,12 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.9.20-alpha.11] - 2026-09-24
6
+
7
+ ### Changed
8
+
9
+ - Subagent orchestration guidance no longer lets an absence of workflow history, or history of only inline runs, push every task inline; the agent judges the task first and refines with execution history and your preferences.
10
+
5
11
  ## [0.9.20-alpha.9] - 2026-09-24
6
12
 
7
13
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/subagents",
3
- "version": "0.9.20-alpha.10",
3
+ "version": "0.9.20-alpha.11",
4
4
  "private": true,
5
5
  "description": "Atomic extension for delegating tasks to subagents with parallel execution. Fork of: https://github.com/nicobailon/pi-subagents",
6
6
  "contributors": [
@@ -17345,7 +17345,7 @@ function parseSubagentNotifyContent(content) {
17345
17345
  // dist/builtin/subagents/src/extension/prompt-guidance.ts
17346
17346
  var DEFAULT_PROMPT_GUIDANCE = [
17347
17347
  `**Subagent orchestration**: Use subagents for focused specialist work inside workflows or as bounded delegation when a workflow would be unnecessary overhead.
17348
- - When the workflow tool is available, decide yourself whether a workflow fits. Prefer one for well-defined work that benefits from durable stages, review loops, recovery or approval gates, and let its stages delegate specialists; work inline for discussion, unclear goals, simple bounded work, or when the user asks to work inline or quickly. Launch with workflow run using the registered workflow name and inputs matching its contract.
17348
+ - When the workflow tool is available, decide yourself whether a workflow fits. Prefer one for well-defined work that benefits from durable stages, review loops, recovery or approval gates, and let its stages delegate specialists; work inline for discussion, unclear goals, simple bounded work, or when the user asks to work inline or quickly. Judge the task's shape first and refine with execution history and user preferences; no workflow history, or history of only inline runs, does not mean every task should run inline. Launch with workflow run using the registered workflow name and inputs matching its contract.
17349
17349
  - Honor the user's task-scoped execution preferences without hidden/nested workflows or pressure to reapprove. Preserve appropriate testing, review and evidence inline, and unrelated safety and authorization constraints.
17350
17350
  - On a switch from an active workflow to inline, notify the controlling session to safely hold/stop the affected run, reconcile completed work and in-flight side effects, then continue inline without duplicate execution. Do not claim completed work was undone.
17351
17351
  - Use a single subagent for a focused specialty or parallel tasks for independent work. Keep substantial-overlap tasks together rather than duplicating investigation across agents.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/web-access",
3
- "version": "0.9.20-alpha.10",
3
+ "version": "0.9.20-alpha.11",
4
4
  "private": true,
5
5
  "description": "Atomic extension for web search, URL fetching, GitHub repo cloning, PDF/video extraction. Fork of: https://github.com/nicobailon/pi-web-access",
6
6
  "contributors": [
@@ -6,6 +6,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.9.20-alpha.11] - 2026-09-24
10
+
11
+ ### Changed
12
+
13
+ - Workflow selection guidance now tells the agent that missing, sparse, or mostly inline workflow history is not by itself a reason to work inline; it judges the task's shape first and refines with execution history and your preferences.
14
+
15
+ ### Fixed
16
+
17
+ - Durable workflows work again on Ubuntu and Debian with the default umask 002. Atomic had refused its own group-writable `~/.atomic` as an ancestor of the PostgreSQL runtime cache and ran workflows in memory, so runs couldn't be resumed after closing Atomic. A group-writable folder is now accepted when its group is your private group: no other account in `/etc/passwd` uses it as its primary group, and `/etc/group` lists no member other than you. World-writable folders and shared groups are still rejected.
18
+ - DBOS no longer launches without its migration lock. Previously, when another process held the lock for more than 60 seconds, or the lock connection or query failed, Atomic launched anyway. Two processes could then migrate the same fresh workflow database at once and fail with duplicate-key errors. Atomic now retries lock contention for up to 60 seconds and reopens a failed or dropped lock connection with increasing delays, as Flyway does. If it still has no lock, launch fails with a clear error instead of running unlocked.
19
+
9
20
  ## [0.9.20-alpha.9] - 2026-09-24
10
21
 
11
22
  ### Breaking Changes
@@ -36,7 +36,7 @@ import {
36
36
  reviewerFailureText,
37
37
  summarizeReviewConvergence,
38
38
  reverify_consolidated_batch
39
- } from "./chunk-twefqrv0.js";
39
+ } from "./chunk-73c5tayt.js";
40
40
  import {
41
41
  VERIFICATION_SCALE
42
42
  } from "./chunk-n1910xc4.js";
@@ -5211,7 +5211,7 @@ import {
5211
5211
  rm,
5212
5212
  writeFile
5213
5213
  } from "node:fs/promises";
5214
- import { homedir } from "node:os";
5214
+ import { homedir, userInfo } from "node:os";
5215
5215
  import { basename, dirname, isAbsolute, join, normalize, relative, sep } from "node:path";
5216
5216
 
5217
5217
  // dist/builtin/workflows/src/durable/local-command.ts
@@ -5570,7 +5570,37 @@ async function findOrCreateRuntimeGeneration(binaries, sourceNativeDir, sourceSn
5570
5570
  await rm(stagedRoot, { recursive: true, force: true });
5571
5571
  }
5572
5572
  }
5573
- async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity(), needsPrivilegeDrop = false, owner, inspect = lstat) {
5573
+ var SYSTEM_ACCOUNT_FILES = { group: "/etc/group", passwd: "/etc/passwd" };
5574
+ async function readAccountRecords(path, gidField) {
5575
+ try {
5576
+ return (await readFile(path, "utf8")).split(/\r?\n/u).map((line) => line.split(":")).filter((fields) => fields.length > gidField && /^\d+$/u.test(fields[gidField]));
5577
+ } catch {
5578
+ return;
5579
+ }
5580
+ }
5581
+ async function isUserPrivateGroup(gid, account, files = SYSTEM_ACCOUNT_FILES) {
5582
+ const groups = await readAccountRecords(files.group, 2);
5583
+ const users = await readAccountRecords(files.passwd, 3);
5584
+ if (groups === undefined || users === undefined)
5585
+ return false;
5586
+ const entries = groups.filter((fields) => Number(fields[2]) === gid);
5587
+ if (entries.length === 0)
5588
+ return false;
5589
+ const primaryMembers = users.filter((fields) => Number(fields[3]) === gid);
5590
+ if (primaryMembers.some((fields) => !/^\d+$/u.test(fields[2]) || Number(fields[2]) !== account.uid))
5591
+ return false;
5592
+ const supplementaryMembers = entries.flatMap((fields) => (fields[3] ?? "").split(",").map((member) => member.trim()).filter((member) => member !== ""));
5593
+ if (supplementaryMembers.some((member) => member !== account.username))
5594
+ return false;
5595
+ return primaryMembers.length + supplementaryMembers.length > 0;
5596
+ }
5597
+ function publisherAccount(publisher) {
5598
+ return {
5599
+ uid: publisher.uid,
5600
+ username: process.getuid?.() === publisher.uid ? userInfo().username : undefined
5601
+ };
5602
+ }
5603
+ async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity(), needsPrivilegeDrop = false, owner, inspect = lstat, privateGroup = (gid) => isUserPrivateGroup(gid, publisherAccount(publisher))) {
5574
5604
  if (!isAbsolute(path))
5575
5605
  throw new Error(`Embedded Postgres runtime cache override must be absolute: ${path}`);
5576
5606
  await mkdir(path, { recursive: true, mode: 493 });
@@ -5580,7 +5610,10 @@ async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity()
5580
5610
  let ancestor = await realpath(path);
5581
5611
  while (true) {
5582
5612
  const info = await inspect(ancestor);
5583
- if (!info.isDirectory() || process.platform !== "win32" && (info.uid !== 0 && info.uid !== publisher.uid || (info.mode & 18) !== 0 && (info.mode & 512) === 0))
5613
+ const sticky = (info.mode & 512) !== 0;
5614
+ const writableByOthers = !sticky && (info.mode & 2) !== 0;
5615
+ const writableByGroup = !sticky && (info.mode & 16) !== 0;
5616
+ if (!info.isDirectory() || process.platform !== "win32" && (info.uid !== 0 && info.uid !== publisher.uid || writableByOthers || writableByGroup && (info.gid !== publisher.gid || !await privateGroup(info.gid))))
5584
5617
  throw new Error(`Untrusted embedded Postgres runtime cache directory ancestor: ${ancestor}`);
5585
5618
  if (needsPrivilegeDrop && owner && publisher.uid === 0 && process.platform !== "win32") {
5586
5619
  const execute = info.uid === owner.uid ? 64 : info.gid === owner.gid ? 8 : 1;
@@ -38,7 +38,7 @@ import {
38
38
  reviewerFailureText,
39
39
  summarizeReviewConvergence,
40
40
  reverify_consolidated_batch
41
- } from "./chunk-twefqrv0.js";
41
+ } from "./chunk-73c5tayt.js";
42
42
  import {
43
43
  fold_usage
44
44
  } from "./chunk-tgt0s5e5.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  goal_default
3
- } from "./chunk-ynded223.js";
4
- import"./chunk-twefqrv0.js";
3
+ } from "./chunk-1q7hfqzd.js";
4
+ import"./chunk-73c5tayt.js";
5
5
  import"./chunk-2377r57g.js";
6
6
  import"./chunk-z0d03ktm.js";
7
7
  import"./chunk-n1910xc4.js";
@@ -14,11 +14,11 @@ import {
14
14
  import {
15
15
  generate_and_filter_default
16
16
  } from "./chunk-7ps7bnb4.js";
17
- import"./chunk-twefqrv0.js";
17
+ import"./chunk-73c5tayt.js";
18
18
  import"./chunk-z0d03ktm.js";
19
19
  import {
20
20
  goal_default
21
- } from "./chunk-ynded223.js";
21
+ } from "./chunk-1q7hfqzd.js";
22
22
  import {
23
23
  open_claude_design_default
24
24
  } from "./chunk-2npg6daz.js";
@@ -27,7 +27,7 @@ import {
27
27
  } from "./chunk-2jv44yz7.js";
28
28
  import {
29
29
  ralph_default
30
- } from "./chunk-ad864596.js";
30
+ } from "./chunk-s2zgzs4j.js";
31
31
  import {
32
32
  tournament_default
33
33
  } from "./chunk-1pd5zcfa.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  ralph_default
3
- } from "./chunk-ad864596.js";
4
- import"./chunk-twefqrv0.js";
3
+ } from "./chunk-s2zgzs4j.js";
4
+ import"./chunk-73c5tayt.js";
5
5
  import"./chunk-2377r57g.js";
6
6
  import"./chunk-z0d03ktm.js";
7
7
  import"./chunk-n1910xc4.js";
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/workflows",
3
- "version": "0.9.20-alpha.10",
3
+ "version": "0.9.20-alpha.11",
4
4
  "private": true,
5
5
  "description": "Atomic extension for multi-stage workflow authoring and execution.",
6
6
  "contributors": [
@@ -30328,43 +30328,76 @@ async function connectLockClient(url) {
30328
30328
  end: async () => await client.end()
30329
30329
  };
30330
30330
  }
30331
- async function acquire(client, pollIntervalMs, maxWaitMs) {
30332
- const deadline = performance.now() + maxWaitMs;
30331
+ function isLaunchLockConnectionError(error) {
30332
+ if (!(error instanceof Error))
30333
+ return false;
30334
+ const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
30335
+ if (code !== undefined && (CONNECTION_ERROR_CODES.has(code) || /^08|^57P0[123]$/u.test(code)))
30336
+ return true;
30337
+ return /connection terminated|connection refused|server closed the connection/iu.test(error.message);
30338
+ }
30339
+ async function closeQuietly(client) {
30340
+ await client.end().catch(() => {
30341
+ return;
30342
+ });
30343
+ }
30344
+ async function acquire(url, options) {
30345
+ const connect = options.connect ?? connectLockClient;
30346
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
30347
+ const maxWaitMs = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;
30348
+ const connectRetries = options.connectRetries ?? DEFAULT_CONNECT_RETRIES;
30349
+ const started = performance.now();
30350
+ const deadline = started + maxWaitMs;
30351
+ let connectFailures = 0;
30352
+ let retryDelayMs = options.connectRetryDelayMs ?? DEFAULT_CONNECT_RETRY_DELAY_MS;
30333
30353
  for (;; ) {
30334
- const result = await client.query("SELECT pg_try_advisory_lock($1::bigint) AS locked", [DBOS_LAUNCH_LOCK_KEY]);
30335
- if (result.rows[0]?.locked === true)
30336
- return true;
30337
- if (performance.now() >= deadline)
30338
- return false;
30339
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
30354
+ let client;
30355
+ try {
30356
+ client = await connect(url);
30357
+ for (;; ) {
30358
+ const result = await client.query("SELECT pg_try_advisory_lock($1::bigint) AS locked", [
30359
+ DBOS_LAUNCH_LOCK_KEY
30360
+ ]);
30361
+ if (result.rows[0]?.locked === true)
30362
+ return client;
30363
+ if (performance.now() >= deadline)
30364
+ throw new DbosLaunchLockTimeoutError(performance.now() - started);
30365
+ await sleep(pollIntervalMs);
30366
+ }
30367
+ } catch (error) {
30368
+ if (client !== undefined)
30369
+ await closeQuietly(client);
30370
+ if (!isLaunchLockConnectionError(error))
30371
+ throw error;
30372
+ connectFailures += 1;
30373
+ if (connectFailures > connectRetries || performance.now() + retryDelayMs >= deadline)
30374
+ throw error;
30375
+ await sleep(retryDelayMs);
30376
+ retryDelayMs = Math.min(retryDelayMs * 2, MAX_CONNECT_RETRY_DELAY_MS);
30377
+ }
30340
30378
  }
30341
30379
  }
30342
30380
  async function withDbosLaunchLock(url, launch, options = {}) {
30343
- const connect = options.connect ?? connectLockClient;
30344
- let client;
30381
+ const client = await acquire(url, options);
30345
30382
  try {
30346
- client = await connect(url);
30347
- } catch {
30348
- return await launch();
30349
- }
30350
- let locked = false;
30351
- try {
30352
- locked = await acquire(client, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS).catch(() => false);
30353
30383
  return await launch();
30354
30384
  } finally {
30355
- if (locked) {
30356
- await client.query("SELECT pg_advisory_unlock($1::bigint) AS locked", [DBOS_LAUNCH_LOCK_KEY]).catch(() => {
30357
- return;
30358
- });
30359
- }
30360
- await client.end().catch(() => {
30385
+ await client.query("SELECT pg_advisory_unlock($1::bigint) AS locked", [DBOS_LAUNCH_LOCK_KEY]).catch(() => {
30361
30386
  return;
30362
30387
  });
30388
+ await closeQuietly(client);
30363
30389
  }
30364
30390
  }
30365
- var DBOS_LAUNCH_LOCK_KEY = "4702111234474983745", LOCK_CONNECT_TIMEOUT_MS = 1e4, DEFAULT_POLL_INTERVAL_MS = 100, DEFAULT_MAX_WAIT_MS = 60000;
30391
+ var DBOS_LAUNCH_LOCK_KEY = "4702111234474983745", LOCK_CONNECT_TIMEOUT_MS = 1e4, DEFAULT_POLL_INTERVAL_MS = 100, DEFAULT_MAX_WAIT_MS = 60000, DEFAULT_CONNECT_RETRIES = 3, DEFAULT_CONNECT_RETRY_DELAY_MS = 250, MAX_CONNECT_RETRY_DELAY_MS = 2000, CONNECTION_ERROR_CODES, DbosLaunchLockTimeoutError, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
30366
30392
  var init_dbos_launch_lock = __esm(() => {
30367
30393
  init_esm();
30394
+ CONNECTION_ERROR_CODES = new Set(["ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "EPIPE", "ENOTFOUND", "EAI_AGAIN"]);
30395
+ DbosLaunchLockTimeoutError = class DbosLaunchLockTimeoutError extends Error {
30396
+ constructor(waitedMs) {
30397
+ super(`Timed out after ${Math.round(waitedMs / 1000)}s waiting for the DBOS launch lock; another process is still launching DBOS against this database. DBOS was not launched.`);
30398
+ this.name = "DbosLaunchLockTimeoutError";
30399
+ }
30400
+ };
30368
30401
  });
30369
30402
 
30370
30403
  // dist/builtin/workflows/src/durable/dbos-managed-health.ts
@@ -86614,7 +86647,7 @@ import {
86614
86647
  rm,
86615
86648
  writeFile
86616
86649
  } from "node:fs/promises";
86617
- import { homedir } from "node:os";
86650
+ import { homedir, userInfo } from "node:os";
86618
86651
  import { basename, dirname as dirname2, isAbsolute, join as join2, normalize, relative, sep } from "node:path";
86619
86652
 
86620
86653
  // dist/builtin/workflows/src/durable/local-command.ts
@@ -86973,7 +87006,37 @@ async function findOrCreateRuntimeGeneration(binaries, sourceNativeDir, sourceSn
86973
87006
  await rm(stagedRoot, { recursive: true, force: true });
86974
87007
  }
86975
87008
  }
86976
- async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity(), needsPrivilegeDrop = false, owner, inspect = lstat) {
87009
+ var SYSTEM_ACCOUNT_FILES = { group: "/etc/group", passwd: "/etc/passwd" };
87010
+ async function readAccountRecords(path, gidField) {
87011
+ try {
87012
+ return (await readFile(path, "utf8")).split(/\r?\n/u).map((line) => line.split(":")).filter((fields) => fields.length > gidField && /^\d+$/u.test(fields[gidField]));
87013
+ } catch {
87014
+ return;
87015
+ }
87016
+ }
87017
+ async function isUserPrivateGroup(gid, account, files = SYSTEM_ACCOUNT_FILES) {
87018
+ const groups = await readAccountRecords(files.group, 2);
87019
+ const users = await readAccountRecords(files.passwd, 3);
87020
+ if (groups === undefined || users === undefined)
87021
+ return false;
87022
+ const entries = groups.filter((fields) => Number(fields[2]) === gid);
87023
+ if (entries.length === 0)
87024
+ return false;
87025
+ const primaryMembers = users.filter((fields) => Number(fields[3]) === gid);
87026
+ if (primaryMembers.some((fields) => !/^\d+$/u.test(fields[2]) || Number(fields[2]) !== account.uid))
87027
+ return false;
87028
+ const supplementaryMembers = entries.flatMap((fields) => (fields[3] ?? "").split(",").map((member) => member.trim()).filter((member) => member !== ""));
87029
+ if (supplementaryMembers.some((member) => member !== account.username))
87030
+ return false;
87031
+ return primaryMembers.length + supplementaryMembers.length > 0;
87032
+ }
87033
+ function publisherAccount(publisher) {
87034
+ return {
87035
+ uid: publisher.uid,
87036
+ username: process.getuid?.() === publisher.uid ? userInfo().username : undefined
87037
+ };
87038
+ }
87039
+ async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity(), needsPrivilegeDrop = false, owner, inspect = lstat, privateGroup = (gid) => isUserPrivateGroup(gid, publisherAccount(publisher))) {
86977
87040
  if (!isAbsolute(path))
86978
87041
  throw new Error(`Embedded Postgres runtime cache override must be absolute: ${path}`);
86979
87042
  await mkdir(path, { recursive: true, mode: 493 });
@@ -86983,7 +87046,10 @@ async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity()
86983
87046
  let ancestor = await realpath(path);
86984
87047
  while (true) {
86985
87048
  const info = await inspect(ancestor);
86986
- if (!info.isDirectory() || process.platform !== "win32" && (info.uid !== 0 && info.uid !== publisher.uid || (info.mode & 18) !== 0 && (info.mode & 512) === 0))
87049
+ const sticky = (info.mode & 512) !== 0;
87050
+ const writableByOthers = !sticky && (info.mode & 2) !== 0;
87051
+ const writableByGroup = !sticky && (info.mode & 16) !== 0;
87052
+ if (!info.isDirectory() || process.platform !== "win32" && (info.uid !== 0 && info.uid !== publisher.uid || writableByOthers || writableByGroup && (info.gid !== publisher.gid || !await privateGroup(info.gid))))
86987
87053
  throw new Error(`Untrusted embedded Postgres runtime cache directory ancestor: ${ancestor}`);
86988
87054
  if (needsPrivilegeDrop && owner && publisher.uid === 0 && process.platform !== "win32") {
86989
87055
  const execute = info.uid === owner.uid ? 64 : info.gid === owner.gid ? 8 : 1;
@@ -97701,7 +97767,7 @@ import { Type as Type16 } from "typebox";
97701
97767
  // dist/builtin/workflows/builtin/open-claude-design-utils.ts
97702
97768
  import { spawnSync } from "node:child_process";
97703
97769
  import { mkdirSync as mkdirSync3 } from "node:fs";
97704
- import { tmpdir as tmpdir2, userInfo } from "node:os";
97770
+ import { tmpdir as tmpdir2, userInfo as userInfo2 } from "node:os";
97705
97771
  import { join as join16 } from "node:path";
97706
97772
  import { Type as Type15 } from "typebox";
97707
97773
  import { createChildProcessEnvironment as createChildProcessEnvironment2 } from "@bastani/atomic";
@@ -97757,7 +97823,7 @@ ${result.text}`).join(`
97757
97823
  function tmpArtifactBase() {
97758
97824
  let user = "default";
97759
97825
  try {
97760
- user = userInfo().username.replace(/[^A-Za-z0-9._-]/g, "_") || "default";
97826
+ user = userInfo2().username.replace(/[^A-Za-z0-9._-]/g, "_") || "default";
97761
97827
  } catch {}
97762
97828
  return join16(tmpdir2(), `open-claude-design-${user}`);
97763
97829
  }
@@ -121968,7 +122034,7 @@ function renderResultBody(result, opts) {
121968
122034
  }
121969
122035
 
121970
122036
  // dist/builtin/workflows/src/extension/workflow-prompts.ts
121971
- var WORKFLOW_SELECTION_GUIDANCE = "Decide yourself whether a workflow fits the request. Use one for well-defined, authorized work that benefits from durable stages, checkpoints, dependencies, recovery, review loops or deliberate approval gates. Work inline for brainstorming, discussion, unclear goals, simple bounded work, or when the user asks to work inline, directly, quickly or without a workflow. Honor an explicit user request for a named workflow. To launch, inspect candidates with list/get/inputs, then call workflow run with the registered workflow name and inputs matching its input contract. Ask only for genuinely missing information.";
122037
+ var WORKFLOW_SELECTION_GUIDANCE = "Decide yourself whether a workflow fits the request. Use one for well-defined, authorized work that benefits from durable stages, checkpoints, dependencies, recovery, review loops or deliberate approval gates. Work inline for brainstorming, discussion, unclear goals, simple bounded work, or when the user asks to work inline, directly, quickly or without a workflow. Judge the task's shape first, then refine the call with execution history and the user's stated or recorded preferences; missing, sparse, or mostly inline workflow history is not by itself a reason to work inline. Honor an explicit user request for a named workflow. To launch, inspect candidates with list/get/inputs, then call workflow run with the registered workflow name and inputs matching its input contract. Ask only for genuinely missing information.";
121972
122038
  var WORKFLOW_TOOL_DESCRIPTION = WORKFLOW_SELECTION_GUIDANCE + " " + "Run starts the named workflow and returns its runId; invalid inputs fail without launching. User /workflow commands launch directly and authored ctx.workflow(...) remains internal composition. " + "When workflow execution fits but another shape would better achieve the task, author a custom TypeScript workflow({...}) inline with normal coding tools, reload it, and run it; after successfully creating and reloading a newly authored custom workflow, report the folder containing its generated code as 'Custom workflow created. You can inspect its code at: <workflow-folder-path>'; do this only for newly created custom workflows, never builtin or pre-existing workflows; " + "discover with list/get/inputs/models, list session runs with status (no runId; statusFilter narrows the list), inspect status/stages/stage details, " + "answer pending prompts only while the root workflow is nonterminal, pause/resume/quit runs, and reload workflow resources. " + "When steering or communication is useful, use Intercom. Before steering a stage, join its invocation group. Use the Intercom `groups` action to discover it. Workflow invocation groups are named `workflow:<rootRunId>`. Then address the stage as `workflow:<rootRunId>/<segment>[/<segment>...]`; each segment may be a stage name, run id, or glob (`*` matches one segment and `**` any depth). Use `intercom list` inside the invocation group to see live, pending, and possible future targets. Live delivery is immediate; a known stage that has not started is queued and receives the message before its first model turn. Name and pattern sends remain sticky for every future matching stage until the root run terminates. When shared scope or acceptance criteria change, broadcast one authoritative update to `workflow:<rootRunId>/**` (or a narrower path pattern) rather than enumerating stages. A syntactically valid target outside the known set queues with a `notInKnownSet` warning and settles undeliverable at terminal only if never delivered. Use `ask` only for a reply-capable live session. " + "Treat a blocked run as continuable by default unless the user requests inline/no-workflow execution: then safely hold/stop it, reconcile completed work and in-flight side effects, and continue inline without duplication. Otherwise resume resumable blocks, answer pending prompts, steer past the obstacle, or start a follow-up workflow past a terminal block; resolve material ambiguity from user intent and repository evidence without bypassing safety or authorization. " + "For action 'run' and 'resume', budget accepts per-field duration, token, cost, and warning overrides; fields resolve over the workflow declaration and config, and 0 disables a field. Pass budget only for a user-specified limit; otherwise omit it and inherit. An estimate is not a budget. " + "For primitive prompt answers, use booleans or the documented confirm labels, exact case-insensitive select labels or 1-based indexes, and text strings for input/editor; an invalid answer remains pending and returns guidance instead of choosing a default. " + "For large stage handoffs, write context to files/artifacts, pass paths via reads, and prompt downstream agents to 'Read the file at <path>...' instead of injecting large previous text. " + "Wrap critical parts of run inputs and steering messages in <keepContext>...</keepContext> so compaction preserves them verbatim in the stages that inherit them; tag role constraints, prohibitions, must-hold criteria, and identifiers, not background or bulk reference material. " + "For transcripts, prefer status/stages/stage to get sessionFile/transcriptPath, " + "quote the exact path without rewriting separators (Windows backslashes are valid), " + "then search it with rg/grep and read small ranges; transcript is path-only by default when sessionFile/transcriptPath exists, explicit tail/limit returns bounded previews, and missing transcript paths fall back to a small preview. " + "Use action 'models' to inspect models in the configured catalog; the result is a configured-auth snapshot showing what's present in the registry with configured authentication, not proof of credentials, entitlements, OAuth freshness, or live provider access. " + "When a user delegates best-stage-model selection for a custom workflow, author model:'auto'; runtime selects from the actual interpolated stage prompt and supplied context. Preserve explicit user concrete model/effort and constraints.";
121973
122039
  var DEFAULT_PROMPT_GUIDANCE = [
121974
122040
  WORKFLOW_SELECTION_GUIDANCE,
@@ -30315,43 +30315,76 @@ async function connectLockClient(url) {
30315
30315
  end: async () => await client.end()
30316
30316
  };
30317
30317
  }
30318
- async function acquire(client, pollIntervalMs, maxWaitMs) {
30319
- const deadline = performance.now() + maxWaitMs;
30318
+ function isLaunchLockConnectionError(error) {
30319
+ if (!(error instanceof Error))
30320
+ return false;
30321
+ const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
30322
+ if (code !== undefined && (CONNECTION_ERROR_CODES.has(code) || /^08|^57P0[123]$/u.test(code)))
30323
+ return true;
30324
+ return /connection terminated|connection refused|server closed the connection/iu.test(error.message);
30325
+ }
30326
+ async function closeQuietly(client) {
30327
+ await client.end().catch(() => {
30328
+ return;
30329
+ });
30330
+ }
30331
+ async function acquire(url, options) {
30332
+ const connect = options.connect ?? connectLockClient;
30333
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
30334
+ const maxWaitMs = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;
30335
+ const connectRetries = options.connectRetries ?? DEFAULT_CONNECT_RETRIES;
30336
+ const started = performance.now();
30337
+ const deadline = started + maxWaitMs;
30338
+ let connectFailures = 0;
30339
+ let retryDelayMs = options.connectRetryDelayMs ?? DEFAULT_CONNECT_RETRY_DELAY_MS;
30320
30340
  for (;; ) {
30321
- const result = await client.query("SELECT pg_try_advisory_lock($1::bigint) AS locked", [DBOS_LAUNCH_LOCK_KEY]);
30322
- if (result.rows[0]?.locked === true)
30323
- return true;
30324
- if (performance.now() >= deadline)
30325
- return false;
30326
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
30341
+ let client;
30342
+ try {
30343
+ client = await connect(url);
30344
+ for (;; ) {
30345
+ const result = await client.query("SELECT pg_try_advisory_lock($1::bigint) AS locked", [
30346
+ DBOS_LAUNCH_LOCK_KEY
30347
+ ]);
30348
+ if (result.rows[0]?.locked === true)
30349
+ return client;
30350
+ if (performance.now() >= deadline)
30351
+ throw new DbosLaunchLockTimeoutError(performance.now() - started);
30352
+ await sleep(pollIntervalMs);
30353
+ }
30354
+ } catch (error) {
30355
+ if (client !== undefined)
30356
+ await closeQuietly(client);
30357
+ if (!isLaunchLockConnectionError(error))
30358
+ throw error;
30359
+ connectFailures += 1;
30360
+ if (connectFailures > connectRetries || performance.now() + retryDelayMs >= deadline)
30361
+ throw error;
30362
+ await sleep(retryDelayMs);
30363
+ retryDelayMs = Math.min(retryDelayMs * 2, MAX_CONNECT_RETRY_DELAY_MS);
30364
+ }
30327
30365
  }
30328
30366
  }
30329
30367
  async function withDbosLaunchLock(url, launch, options = {}) {
30330
- const connect = options.connect ?? connectLockClient;
30331
- let client;
30332
- try {
30333
- client = await connect(url);
30334
- } catch {
30335
- return await launch();
30336
- }
30337
- let locked = false;
30368
+ const client = await acquire(url, options);
30338
30369
  try {
30339
- locked = await acquire(client, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS).catch(() => false);
30340
30370
  return await launch();
30341
30371
  } finally {
30342
- if (locked) {
30343
- await client.query("SELECT pg_advisory_unlock($1::bigint) AS locked", [DBOS_LAUNCH_LOCK_KEY]).catch(() => {
30344
- return;
30345
- });
30346
- }
30347
- await client.end().catch(() => {
30372
+ await client.query("SELECT pg_advisory_unlock($1::bigint) AS locked", [DBOS_LAUNCH_LOCK_KEY]).catch(() => {
30348
30373
  return;
30349
30374
  });
30375
+ await closeQuietly(client);
30350
30376
  }
30351
30377
  }
30352
- var DBOS_LAUNCH_LOCK_KEY = "4702111234474983745", LOCK_CONNECT_TIMEOUT_MS = 1e4, DEFAULT_POLL_INTERVAL_MS = 100, DEFAULT_MAX_WAIT_MS = 60000;
30378
+ var DBOS_LAUNCH_LOCK_KEY = "4702111234474983745", LOCK_CONNECT_TIMEOUT_MS = 1e4, DEFAULT_POLL_INTERVAL_MS = 100, DEFAULT_MAX_WAIT_MS = 60000, DEFAULT_CONNECT_RETRIES = 3, DEFAULT_CONNECT_RETRY_DELAY_MS = 250, MAX_CONNECT_RETRY_DELAY_MS = 2000, CONNECTION_ERROR_CODES, DbosLaunchLockTimeoutError, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
30353
30379
  var init_dbos_launch_lock = __esm(() => {
30354
30380
  init_esm();
30381
+ CONNECTION_ERROR_CODES = new Set(["ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "EPIPE", "ENOTFOUND", "EAI_AGAIN"]);
30382
+ DbosLaunchLockTimeoutError = class DbosLaunchLockTimeoutError extends Error {
30383
+ constructor(waitedMs) {
30384
+ super(`Timed out after ${Math.round(waitedMs / 1000)}s waiting for the DBOS launch lock; another process is still launching DBOS against this database. DBOS was not launched.`);
30385
+ this.name = "DbosLaunchLockTimeoutError";
30386
+ }
30387
+ };
30355
30388
  });
30356
30389
 
30357
30390
  // dist/builtin/workflows/src/durable/dbos-managed-health.ts
@@ -39742,7 +39775,7 @@ import {
39742
39775
  rm,
39743
39776
  writeFile
39744
39777
  } from "node:fs/promises";
39745
- import { homedir } from "node:os";
39778
+ import { homedir, userInfo } from "node:os";
39746
39779
  import { basename as basename2, dirname, isAbsolute, join, normalize, relative, sep } from "node:path";
39747
39780
 
39748
39781
  // dist/builtin/workflows/src/durable/local-command.ts
@@ -40101,7 +40134,37 @@ async function findOrCreateRuntimeGeneration(binaries, sourceNativeDir, sourceSn
40101
40134
  await rm(stagedRoot, { recursive: true, force: true });
40102
40135
  }
40103
40136
  }
40104
- async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity(), needsPrivilegeDrop = false, owner, inspect = lstat) {
40137
+ var SYSTEM_ACCOUNT_FILES = { group: "/etc/group", passwd: "/etc/passwd" };
40138
+ async function readAccountRecords(path, gidField) {
40139
+ try {
40140
+ return (await readFile(path, "utf8")).split(/\r?\n/u).map((line) => line.split(":")).filter((fields) => fields.length > gidField && /^\d+$/u.test(fields[gidField]));
40141
+ } catch {
40142
+ return;
40143
+ }
40144
+ }
40145
+ async function isUserPrivateGroup(gid, account, files = SYSTEM_ACCOUNT_FILES) {
40146
+ const groups = await readAccountRecords(files.group, 2);
40147
+ const users = await readAccountRecords(files.passwd, 3);
40148
+ if (groups === undefined || users === undefined)
40149
+ return false;
40150
+ const entries = groups.filter((fields) => Number(fields[2]) === gid);
40151
+ if (entries.length === 0)
40152
+ return false;
40153
+ const primaryMembers = users.filter((fields) => Number(fields[3]) === gid);
40154
+ if (primaryMembers.some((fields) => !/^\d+$/u.test(fields[2]) || Number(fields[2]) !== account.uid))
40155
+ return false;
40156
+ const supplementaryMembers = entries.flatMap((fields) => (fields[3] ?? "").split(",").map((member) => member.trim()).filter((member) => member !== ""));
40157
+ if (supplementaryMembers.some((member) => member !== account.username))
40158
+ return false;
40159
+ return primaryMembers.length + supplementaryMembers.length > 0;
40160
+ }
40161
+ function publisherAccount(publisher) {
40162
+ return {
40163
+ uid: publisher.uid,
40164
+ username: process.getuid?.() === publisher.uid ? userInfo().username : undefined
40165
+ };
40166
+ }
40167
+ async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity(), needsPrivilegeDrop = false, owner, inspect = lstat, privateGroup = (gid) => isUserPrivateGroup(gid, publisherAccount(publisher))) {
40105
40168
  if (!isAbsolute(path))
40106
40169
  throw new Error(`Embedded Postgres runtime cache override must be absolute: ${path}`);
40107
40170
  await mkdir(path, { recursive: true, mode: 493 });
@@ -40111,7 +40174,10 @@ async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity()
40111
40174
  let ancestor = await realpath(path);
40112
40175
  while (true) {
40113
40176
  const info = await inspect(ancestor);
40114
- if (!info.isDirectory() || process.platform !== "win32" && (info.uid !== 0 && info.uid !== publisher.uid || (info.mode & 18) !== 0 && (info.mode & 512) === 0))
40177
+ const sticky = (info.mode & 512) !== 0;
40178
+ const writableByOthers = !sticky && (info.mode & 2) !== 0;
40179
+ const writableByGroup = !sticky && (info.mode & 16) !== 0;
40180
+ if (!info.isDirectory() || process.platform !== "win32" && (info.uid !== 0 && info.uid !== publisher.uid || writableByOthers || writableByGroup && (info.gid !== publisher.gid || !await privateGroup(info.gid))))
40115
40181
  throw new Error(`Untrusted embedded Postgres runtime cache directory ancestor: ${ancestor}`);
40116
40182
  if (needsPrivilegeDrop && owner && publisher.uid === 0 && process.platform !== "win32") {
40117
40183
  const execute = info.uid === owner.uid ? 64 : info.gid === owner.gid ? 8 : 1;
@@ -69,7 +69,7 @@ function buildRules(selectedTools, toolGuidelines, promptGuidelines) {
69
69
  " - When you author a commit, PR, issue, or issue/review comment for a task, record how it ran: `Assistant-workflow: <workflow name> (run <runId>)` for a registered or custom workflow, or `Assistant-workflow: inline` when no workflow was used; and `Assistant-duration: <elapsed> <converged|blocked|abandoned>, estimated <estimate>` (for example `Assistant-duration: 42m converged, estimated 30m`), measuring wall-clock time from launch or task start until acceptance was proven or work stopped, including resumes and repair rounds. Take elapsed time from workflow status timing or timestamps you recorded (for example `date` at task start); write `unmeasured` rather than guess. Put these as trailers alongside `Assistant-model` in commits (git trailers, or the equivalent commit-message metadata in the repository's version control system) and as the same `Key: value` lines in PR/merge request, issue, and comment bodies. For multi-commit work, record the workflow on each commit and the final duration once, in the last commit or the PR body.",
70
70
  " - In the same artifacts, record how the result was verified with one `Assistant-verification: <method> <passed|failed|unavailable>: <what it proved or why>` line per method that actually ran or was attempted (for example `Assistant-verification: herdr terminal E2E passed: /tasks lists running tasks first at 80x24`, `Assistant-verification: vitest unit passed: npm run test:unit`, or `Assistant-verification: cua-driver unavailable: Accessibility permission not granted`). Name the concrete mechanism, such as unit, integration, or E2E tests, agent-browser, Cua Driver, herdr or tmux terminal automation, the qlty CLI, typecheck or lint, or a manual scenario, and the command or scenario it exercised. Record only checks that ran and their observed outcome; never record a skipped, mocked, or planned check as passed.",
71
71
  " - When the user states or reveals a durable preference about how they work (a correction, a rejected approach, scope, review, tooling, or communication style), record it in the same artifacts as `User-preference: <one line, in the user's terms>`, and tie it to the requesting user with a `Co-authored-by: <name> <email>` trailer taken from their version control identity (for example `git config user.name`/`user.email`) unless that line is already present; in PR, issue, and comment bodies, add the same line or their hosting account (for example from `gh api user`). Record only what the user expressed or their own edits show; never record secrets, credentials, or personal details unrelated to the work. If repository rules restrict commit or PR formats, fit the records into what they allow.",
72
- " - Before choosing between a workflow and inline work, choosing how to verify a change, estimating a duration, or interpreting an ambiguous request, mine these records with the rest of the history using the repository's version control system and its hosting CLI, for example `git log --format='%h %an <%ae> %s%n%(trailers:key=Assistant-workflow,key=Assistant-duration,key=Assistant-verification,key=User-preference,key=Co-authored-by)'` with `gh pr list --state all --search 'Assistant-workflow in:body'` on GitHub, or the equivalent commands for other systems and hosts (for example `glab` on GitLab). Compare tasks of similar kind and size, and state the sample size with the median and range. Treat fewer than five comparable records as anecdotal, and prefer the more recent record when two conflict. When choosing verification, start from the methods that proved comparable changes (the same files, subsystem, or kind of change), reuse their commands and scenarios, and do not retry a setup recorded as `unavailable` without a reason to expect a different result; past records never replace the project's required checks. Prioritize preferences tied to the requesting user by their co-author line, commit author, or hosting account. When the user has none that cover the situation, fall back to other contributors' relevant preferences as repository conventions; the user's own records and current request override them, so users can always encode their own preference. This history is a guide, not the decision: the current request, the task itself, and explicit user instructions decide between a workflow and inline work.",
72
+ " - Before choosing between a workflow and inline work, choosing how to verify a change, estimating a duration, or interpreting an ambiguous request, mine these records with the rest of the history using the repository's version control system and its hosting CLI, for example `git log --format='%h %an <%ae> %s%n%(trailers:key=Assistant-workflow,key=Assistant-duration,key=Assistant-verification,key=User-preference,key=Co-authored-by)'` with `gh pr list --state all --search 'Assistant-workflow in:body'` on GitHub, or the equivalent commands for other systems and hosts (for example `glab` on GitLab). Compare tasks of similar kind and size, and state the sample size with the median and range. Treat fewer than five comparable records as anecdotal, and prefer the more recent record when two conflict. When choosing verification, start from the methods that proved comparable changes (the same files, subsystem, or kind of change), reuse their commands and scenarios, and do not retry a setup recorded as `unavailable` without a reason to expect a different result; past records never replace the project's required checks. Prioritize preferences tied to the requesting user by their co-author line, commit author, or hosting account. When the user has none that cover the situation, fall back to other contributors' relevant preferences as repository conventions; the user's own records and current request override them, so users can always encode their own preference. This history is a guide, not the decision: the current request, the task itself, and explicit user instructions decide between a workflow and inline work. Missing, sparse, or mostly inline workflow history is not evidence that the user prefers inline work: records exist only for tasks that wrote them, and past inline runs may reflect an earlier default rather than a choice. Without a recorded or stated preference that covers the situation, judge the task's shape yourself and choose a workflow when it would help, then let comparable records and the user's preferences refine that call.",
73
73
  ].join("\n"));
74
74
  }
75
75
  for (const name of selectedTools) {
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE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I,CAAC;IACrD,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getSystemMessageText } from \"@bastani/pi-ai\";\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nconst DEFAULT_PROMPT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"find\", \"search\", \"ask_user_question\", \"todo\"] as const;\n\nexport interface SystemPromptModel {\n\t/** Provider identifier for the selected model. */\n\tprovider: string;\n\t/** Stable provider-specific model identifier. */\n\tid: string;\n\t/** Human-readable model name, when available. */\n\tname?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces the default prefix). */\n\tcustomPrompt?: string;\n\t/** Exact full prompt replacement set by a before_agent_start handler. */\n\tforceSystemPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, find, search, ask_user_question, todo] */\n\tselectedTools?: string[];\n\t/** Tool names explicitly excluded by the caller and omitted from generated guidance. */\n\texcludedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Guideline bullets contributed by each tool, keyed by tool name. */\n\ttoolGuidelines?: Record<string, string[]>;\n\t/** Additional guideline bullets appended to the default system prompt rules. */\n\tpromptGuidelines?: string[];\n\t/** Text appended from user configuration before project context, skills, and cwd. */\n\tappendSystemPrompt?: string;\n\t/** Additional XML-wrapped prompt sections keyed by tag name. */\n\tsections?: Record<string, string>;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Currently selected model, used for model-aware prompt metadata. */\n\tselectedModel?: SystemPromptModel;\n\t/** Current reasoning/thinking level for the selected model. */\n\tselectedThinkingLevel?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\nexport type NormalizedBuildSystemPromptOptions = BuildSystemPromptOptions & {\n\tselectedTools: string[];\n\ttoolSnippets: Record<string, string>;\n\ttoolGuidelines: Record<string, string[]>;\n\tpromptGuidelines: string[];\n\tappendSystemPrompt: string;\n\tsections: Record<string, string>;\n\tcontextFiles: Array<{ path: string; content: string }>;\n\tskills: Skill[];\n};\n\n/**\n * Ordered system prompt sections, keyed by name. `preamble` is untagged text; every other\n * section is wrapped in a tag of the same name so the model can match later updates to it.\n * These become `SystemMessage.sections` in the transcript.\n */\nexport type SystemPromptSections = Record<string, string>;\n\nconst SYSTEM_PROMPT_SECTION_NAME = /^[a-z][a-z0-9_-]*$/;\n/** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */\nexport function normalizeBuildSystemPromptOptions(input: BuildSystemPromptOptions): NormalizedBuildSystemPromptOptions {\n\treturn {\n\t\tcustomPrompt: input.customPrompt,\n\t\tforceSystemPrompt: input.forceSystemPrompt,\n\t\tselectedTools: [...(input.selectedTools ?? DEFAULT_PROMPT_TOOLS)],\n\t\ttoolSnippets: { ...(input.toolSnippets ?? {}) },\n\t\ttoolGuidelines: Object.fromEntries(\n\t\t\tObject.entries(input.toolGuidelines ?? {}).map(([name, guidelines]) => [name, [...guidelines]]),\n\t\t),\n\t\tpromptGuidelines: [...(input.promptGuidelines ?? [])],\n\t\tappendSystemPrompt: input.appendSystemPrompt ?? \"\",\n\t\tsections: { ...(input.sections ?? {}) },\n\t\tcwd: input.cwd,\n\t\t...(input.excludedTools === undefined ? {} : { excludedTools: [...input.excludedTools] }),\n\t\t...(input.selectedModel === undefined ? {} : { selectedModel: { ...input.selectedModel } }),\n\t\t...(input.selectedThinkingLevel === undefined ? {} : { selectedThinkingLevel: input.selectedThinkingLevel }),\n\t\tcontextFiles: (input.contextFiles ?? []).map((file) => ({ ...file })),\n\t\tskills: (input.skills ?? []).map((skill) => ({ ...skill })),\n\t};\n}\n\nfunction renderProjectContext(contextFiles: Array<{ path: string; content: string }>): string {\n\treturn [\n\t\t\"Project-specific instructions and guidelines:\",\n\t\t...contextFiles.map(\n\t\t\t({ path, content }) => `<project_instructions path=\"${path}\">\\n${content}\\n</project_instructions>`,\n\t\t),\n\t].join(\"\\n\\n\");\n}\n\nfunction buildRules(\n\tselectedTools: string[],\n\ttoolGuidelines: Record<string, string[]>,\n\tpromptGuidelines: string[],\n): string {\n\tconst rules: string[] = [];\n\tconst seen = new Set<string>();\n\tconst addRule = (rule: string): void => {\n\t\tconst normalized = rule.trim();\n\t\tif (!normalized || seen.has(normalized)) return;\n\t\tseen.add(normalized);\n\t\trules.push(normalized);\n\t};\n\n\tconst tools = selectedTools;\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasPowerShell = tools.includes(\"powershell\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst shouldIncludeAskUserFallbackGuidance = tools.length > 0 && !tools.includes(\"ask_user_question\");\n\tconst addGuideline = addRule;\n\tif ((hasBash || hasPowerShell) && !hasFind && !hasLs) {\n\t\tif (hasBash && hasPowerShell) {\n\t\t\taddRule(\"Use bash or PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else if (hasPowerShell) {\n\t\t\taddRule(\"Use PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else {\n\t\t\taddRule(\"Use bash for file operations like ls, rg, find\");\n\t\t}\n\t}\n\tif (shouldIncludeAskUserFallbackGuidance) {\n\t\taddGuideline(\n\t\t\t\"If an equivalent user-question tool is available, use it for all questions to the user instead of plain text, including confirmations and approvals, following its supported schema. When no usable question tool or human-input channel exists, do not stall on a question: choose the interpretation best supported by the repository and the stated objective, state the assumption in your response, and continue fully autonomously on best judgment. Tool unavailability alone is not a blocker. Preserve safety and authorization constraints.\",\n\t\t);\n\t}\n\tif (hasBash || hasPowerShell) {\n\t\taddGuideline(\n\t\t\t\"**Repository intent**: When working in a repository, infer how its maintainers actually work before imposing defaults: review recent commits, open and merged PRs, issues and their comments, and project/board status when tooling allows (for example `git log` and the `gh` CLI) to learn conventions, priorities, and scope norms. Better, identify the requesting user (`git config user.name`/`user.email`, `gh api user`) and study their own commits, PRs, reviews, and issue comments so you interpret ambiguous requests the way they would, aligning style, scope, and process with their patterns.\",\n\t\t);\n\t\taddGuideline(\n\t\t\t[\n\t\t\t\t\"**Execution history**: Leave a mineable record of how each task was executed and what the user prefers, and mine those records to calibrate later work. The records only accumulate value if every task writes them. If the user, a context file, or `APPEND_SYSTEM.md` asks you not to record some or all of these records, skip those records.\",\n\t\t\t\t\" - When you author a commit, PR, issue, or issue/review comment for a task, record how it ran: `Assistant-workflow: <workflow name> (run <runId>)` for a registered or custom workflow, or `Assistant-workflow: inline` when no workflow was used; and `Assistant-duration: <elapsed> <converged|blocked|abandoned>, estimated <estimate>` (for example `Assistant-duration: 42m converged, estimated 30m`), measuring wall-clock time from launch or task start until acceptance was proven or work stopped, including resumes and repair rounds. Take elapsed time from workflow status timing or timestamps you recorded (for example `date` at task start); write `unmeasured` rather than guess. Put these as trailers alongside `Assistant-model` in commits (git trailers, or the equivalent commit-message metadata in the repository's version control system) and as the same `Key: value` lines in PR/merge request, issue, and comment bodies. For multi-commit work, record the workflow on each commit and the final duration once, in the last commit or the PR body.\",\n\t\t\t\t\" - In the same artifacts, record how the result was verified with one `Assistant-verification: <method> <passed|failed|unavailable>: <what it proved or why>` line per method that actually ran or was attempted (for example `Assistant-verification: herdr terminal E2E passed: /tasks lists running tasks first at 80x24`, `Assistant-verification: vitest unit passed: npm run test:unit`, or `Assistant-verification: cua-driver unavailable: Accessibility permission not granted`). Name the concrete mechanism, such as unit, integration, or E2E tests, agent-browser, Cua Driver, herdr or tmux terminal automation, the qlty CLI, typecheck or lint, or a manual scenario, and the command or scenario it exercised. Record only checks that ran and their observed outcome; never record a skipped, mocked, or planned check as passed.\",\n\t\t\t\t\" - When the user states or reveals a durable preference about how they work (a correction, a rejected approach, scope, review, tooling, or communication style), record it in the same artifacts as `User-preference: <one line, in the user's terms>`, and tie it to the requesting user with a `Co-authored-by: <name> <email>` trailer taken from their version control identity (for example `git config user.name`/`user.email`) unless that line is already present; in PR, issue, and comment bodies, add the same line or their hosting account (for example from `gh api user`). Record only what the user expressed or their own edits show; never record secrets, credentials, or personal details unrelated to the work. If repository rules restrict commit or PR formats, fit the records into what they allow.\",\n\t\t\t\t\" - Before choosing between a workflow and inline work, choosing how to verify a change, estimating a duration, or interpreting an ambiguous request, mine these records with the rest of the history using the repository's version control system and its hosting CLI, for example `git log --format='%h %an <%ae> %s%n%(trailers:key=Assistant-workflow,key=Assistant-duration,key=Assistant-verification,key=User-preference,key=Co-authored-by)'` with `gh pr list --state all --search 'Assistant-workflow in:body'` on GitHub, or the equivalent commands for other systems and hosts (for example `glab` on GitLab). Compare tasks of similar kind and size, and state the sample size with the median and range. Treat fewer than five comparable records as anecdotal, and prefer the more recent record when two conflict. When choosing verification, start from the methods that proved comparable changes (the same files, subsystem, or kind of change), reuse their commands and scenarios, and do not retry a setup recorded as `unavailable` without a reason to expect a different result; past records never replace the project's required checks. Prioritize preferences tied to the requesting user by their co-author line, commit author, or hosting account. When the user has none that cover the situation, fall back to other contributors' relevant preferences as repository conventions; the user's own records and current request override them, so users can always encode their own preference. This history is a guide, not the decision: the current request, the task itself, and explicit user instructions decide between a workflow and inline work.\",\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n\n\tfor (const name of selectedTools) {\n\t\tfor (const rule of toolGuidelines[name] ?? []) addRule(rule);\n\t}\n\tfor (const rule of promptGuidelines) addRule(rule);\n\taddRule(\n\t\t\"Write self-describing code and do not add comments unless the user explicitly asks for them or the task instructions call for them. Code that needs a comment to be understood is a smell: restructure it with clearer names, smaller units, or explicit types instead\",\n\t);\n\taddRule(\"Be concise in your responses\");\n\taddRule(\"Show file paths clearly when working with files\");\n\treturn rules.map((rule) => `- ${rule}`).join(\"\\n\");\n}\n\n/** Build the ordered, independently replaceable sections of the structured system prompt. */\nexport function buildSystemPromptSections(input: BuildSystemPromptOptions): SystemPromptSections {\n\tconst options = normalizeBuildSystemPromptOptions(input);\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\ttoolGuidelines,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tsections: customSections,\n\t\tcwd,\n\t\tcontextFiles,\n\t\tskills,\n\t} = options;\n\tconst explicitlyExcludedTools = new Set(options.excludedTools ?? []);\n\tconst tools = selectedTools.filter((name) => !explicitlyExcludedTools.has(name));\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\tconst modelName = options.selectedModel?.name?.trim() || options.selectedModel?.id || \"unknown\";\n\tconst modelReasoningLevel = options.selectedThinkingLevel?.trim() || \"off\";\n\tconst now = new Date();\n\tconst date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}`;\n\n\tfor (const name of Object.keys(customSections)) {\n\t\tif (!SYSTEM_PROMPT_SECTION_NAME.test(name) || name === \"preamble\") {\n\t\t\tthrow new Error(`Invalid system prompt section name: ${name}`);\n\t\t}\n\t}\n\n\tconst promptSections: Record<string, string> = {};\n\tif (customPrompt) {\n\t\tpromptSections.preamble = customPrompt;\n\t} else {\n\t\tpromptSections.preamble =\n\t\t\t\"You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\";\n\t\tconst visibleTools = tools.filter((name) => !!toolSnippets[name]);\n\t\tconst toolsList =\n\t\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join(\"\\n\") : \"(none)\";\n\t\tpromptSections.tools = `Available tools:\\n${toolsList}\\n\\nIn addition to the tools above, you may have access to other custom tools depending on the project.`;\n\t\tpromptSections.rules = `Guidelines:\\n${buildRules(tools, toolGuidelines, promptGuidelines)}`;\n\t\tpromptSections.docs = `\nAtomic documentation (read when the user asks about model choice, computer use or automation, MCP, web access, intercom, subagents, or customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)\n- Bundled integrations use the same docs root in npm and binary installations: MCP servers (docs/mcp-servers.md), web access (docs/web-access.md), intercom (docs/intercom.md), subagents (docs/subagents.md), workflows (docs/workflows.md). Read these guides rather than guessing paths inside builtin packages.\n- When the user asks which model to choose for a task, read ${docsPath}/models/model-selection.md and ${docsPath}/models/evals.md, then consult https://artificialanalysis.ai/ for the relevant benchmark charts and methodology. Match the task to individual evaluations rather than an aggregate winner. Cite the benchmark, source date, exact model/effort and cost or latency tradeoff; distinguish measured results from recommendations. If live evidence is unavailable, label the dated docs snapshot instead of claiming a refresh. Check the configured catalog before giving an exact provider/model or thinking setting; catalog presence is not proof of live access.\n- For computer use (CUA) on desktop apps, simulators and emulators, use Cua Driver through the bundled cua-driver skill and one-shot \\`cua-driver call <tool>\\` commands: when a model chooses the next action (interactive sessions or any workflow stage acting outside ctx.tool), use the CLI; when workflow TypeScript code owns the sequence and postcondition, use the @trycua/cua-driver TypeScript SDK inside ctx.tool. If \\`cua-driver --version\\` fails, make one bounded attempt with upstream's one-line executable installer and report its side effects. The executable installer does not install an agent skill; ignore upstream README's optional skill-install steps, never run \\`cua-driver skills install\\` or \\`clawhub install @cua/driver\\`, and do not link or copy a skill into \\`~/.agents/skills/cua-driver\\`. Atomic already bundles it; leave any existing user-level skill alone. Run every cua-driver command with CUA_DRIVER_RS_TELEMETRY_ENABLED=false and follow ${docsPath}/computer-use.md for install, readiness and permissions. Prefer the agent-browser skill for what it covers: websites and web apps in Chrome/Chromium, Electron desktop apps such as VS Code, Slack, Discord, Figma, Notion and Spotify, Slack workspaces, and cloud browsers. Use cua-driver for everything else (native desktop apps, iOS simulators, Android emulators, OS dialogs and permission prompts, non-Chromium browsers) and whenever agent-browser hits a limitation. For terminal automation/testing, prefer herdr on macOS, Linux and Windows; install it if missing when network access and permissions permit, and fall back to tmux or native Windows psmux if installation or use is not possible. Load the matching skill and ${docsPath}/workflows/verification.md. Preserve the pinned herdr skill's explicit-request and HERDR_ENV=1 requirements; never control a focused session from outside Herdr. Check installed capabilities, use dedicated sessions, respect desktop permissions, and stop before destructive actions. These CLIs are not interchangeable, and skills do not grant tools or authorization.\n- Also skip \\`cua-driver skills update\\` and any skill installation into other agent directories such as \\`~/.claude/skills\\`; updating the executable is separate from installing or updating a skill.\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\t}\n\n\tif (appendSystemPrompt) promptSections.addendum = appendSystemPrompt;\n\tif (contextFiles.length > 0) promptSections.project_context = renderProjectContext(contextFiles);\n\tconst skillFileReadTool = ([\"read\", \"bash\"] as const).find((tool) => tools.includes(tool));\n\tif (skillFileReadTool && skills.length > 0) {\n\t\tconst skillsPrompt = formatSkillsForPrompt(skills, skillFileReadTool).trim();\n\t\tif (skillsPrompt) promptSections.skills = skillsPrompt;\n\t}\n\tpromptSections.model = `Model name (used for commit attribution): ${modelName}\\nModel reasoning level: ${modelReasoningLevel}`;\n\tpromptSections.date = `Current date: ${date}`;\n\tpromptSections.cwd = `Current working directory: ${cwd.replace(/\\\\/g, \"/\")}`;\n\tfor (const [name, content] of Object.entries(customSections)) {\n\t\tif (content) promptSections[name] = content;\n\t}\n\n\tconst sections: SystemPromptSections = { preamble: promptSections.preamble };\n\tfor (const [name, content] of Object.entries(promptSections)) {\n\t\tif (name !== \"preamble\") sections[name] = `<${name}>\\n${content}\\n</${name}>`;\n\t}\n\treturn sections;\n}\n\n/**\n * The complete prompt state for `input`. A forced prompt is opaque and lives in `content`\n * with no sections; otherwise `content` is empty and the structured sections carry the prompt.\n */\nexport function buildSystemPromptState(input: BuildSystemPromptOptions): {\n\tcontent: string;\n\tsections?: SystemPromptSections;\n} {\n\tif (input.forceSystemPrompt !== undefined) return { content: input.forceSystemPrompt };\n\treturn { content: \"\", sections: buildSystemPromptSections(input) };\n}\n\n/** Build the system prompt text, rendered exactly as the transcript's system message replays it. */\nexport function buildSystemPrompt(input: BuildSystemPromptOptions): string {\n\treturn getSystemMessageText({ role: \"system\", ...buildSystemPromptState(input), timestamp: 0 });\n}\n\n/**\n * Diff the sections the model currently has (replayed from the transcript, so never null)\n * against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when\n * nothing changed.\n */\nexport function diffSystemPromptSections(\n\tprevious: Record<string, string | null>,\n\tcurrent: SystemPromptSections,\n): Record<string, string | null> | undefined {\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(current)) {\n\t\tif (previous[name] !== text) patch[name] = text;\n\t}\n\tfor (const name of Object.keys(previous)) {\n\t\tif (current[name] === undefined) patch[name] = null;\n\t}\n\treturn Object.keys(patch).length > 0 ? patch : undefined;\n}\n"]}
1
+ {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,MAAM,oBAAoB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,E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MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getSystemMessageText } from \"@bastani/pi-ai\";\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nconst DEFAULT_PROMPT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"find\", \"search\", \"ask_user_question\", \"todo\"] as const;\n\nexport interface SystemPromptModel {\n\t/** Provider identifier for the selected model. */\n\tprovider: string;\n\t/** Stable provider-specific model identifier. */\n\tid: string;\n\t/** Human-readable model name, when available. */\n\tname?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces the default prefix). */\n\tcustomPrompt?: string;\n\t/** Exact full prompt replacement set by a before_agent_start handler. */\n\tforceSystemPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, find, search, ask_user_question, todo] */\n\tselectedTools?: string[];\n\t/** Tool names explicitly excluded by the caller and omitted from generated guidance. */\n\texcludedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Guideline bullets contributed by each tool, keyed by tool name. */\n\ttoolGuidelines?: Record<string, string[]>;\n\t/** Additional guideline bullets appended to the default system prompt rules. */\n\tpromptGuidelines?: string[];\n\t/** Text appended from user configuration before project context, skills, and cwd. */\n\tappendSystemPrompt?: string;\n\t/** Additional XML-wrapped prompt sections keyed by tag name. */\n\tsections?: Record<string, string>;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Currently selected model, used for model-aware prompt metadata. */\n\tselectedModel?: SystemPromptModel;\n\t/** Current reasoning/thinking level for the selected model. */\n\tselectedThinkingLevel?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\nexport type NormalizedBuildSystemPromptOptions = BuildSystemPromptOptions & {\n\tselectedTools: string[];\n\ttoolSnippets: Record<string, string>;\n\ttoolGuidelines: Record<string, string[]>;\n\tpromptGuidelines: string[];\n\tappendSystemPrompt: string;\n\tsections: Record<string, string>;\n\tcontextFiles: Array<{ path: string; content: string }>;\n\tskills: Skill[];\n};\n\n/**\n * Ordered system prompt sections, keyed by name. `preamble` is untagged text; every other\n * section is wrapped in a tag of the same name so the model can match later updates to it.\n * These become `SystemMessage.sections` in the transcript.\n */\nexport type SystemPromptSections = Record<string, string>;\n\nconst SYSTEM_PROMPT_SECTION_NAME = /^[a-z][a-z0-9_-]*$/;\n/** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */\nexport function normalizeBuildSystemPromptOptions(input: BuildSystemPromptOptions): NormalizedBuildSystemPromptOptions {\n\treturn {\n\t\tcustomPrompt: input.customPrompt,\n\t\tforceSystemPrompt: input.forceSystemPrompt,\n\t\tselectedTools: [...(input.selectedTools ?? DEFAULT_PROMPT_TOOLS)],\n\t\ttoolSnippets: { ...(input.toolSnippets ?? {}) },\n\t\ttoolGuidelines: Object.fromEntries(\n\t\t\tObject.entries(input.toolGuidelines ?? {}).map(([name, guidelines]) => [name, [...guidelines]]),\n\t\t),\n\t\tpromptGuidelines: [...(input.promptGuidelines ?? [])],\n\t\tappendSystemPrompt: input.appendSystemPrompt ?? \"\",\n\t\tsections: { ...(input.sections ?? {}) },\n\t\tcwd: input.cwd,\n\t\t...(input.excludedTools === undefined ? {} : { excludedTools: [...input.excludedTools] }),\n\t\t...(input.selectedModel === undefined ? {} : { selectedModel: { ...input.selectedModel } }),\n\t\t...(input.selectedThinkingLevel === undefined ? {} : { selectedThinkingLevel: input.selectedThinkingLevel }),\n\t\tcontextFiles: (input.contextFiles ?? []).map((file) => ({ ...file })),\n\t\tskills: (input.skills ?? []).map((skill) => ({ ...skill })),\n\t};\n}\n\nfunction renderProjectContext(contextFiles: Array<{ path: string; content: string }>): string {\n\treturn [\n\t\t\"Project-specific instructions and guidelines:\",\n\t\t...contextFiles.map(\n\t\t\t({ path, content }) => `<project_instructions path=\"${path}\">\\n${content}\\n</project_instructions>`,\n\t\t),\n\t].join(\"\\n\\n\");\n}\n\nfunction buildRules(\n\tselectedTools: string[],\n\ttoolGuidelines: Record<string, string[]>,\n\tpromptGuidelines: string[],\n): string {\n\tconst rules: string[] = [];\n\tconst seen = new Set<string>();\n\tconst addRule = (rule: string): void => {\n\t\tconst normalized = rule.trim();\n\t\tif (!normalized || seen.has(normalized)) return;\n\t\tseen.add(normalized);\n\t\trules.push(normalized);\n\t};\n\n\tconst tools = selectedTools;\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasPowerShell = tools.includes(\"powershell\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst shouldIncludeAskUserFallbackGuidance = tools.length > 0 && !tools.includes(\"ask_user_question\");\n\tconst addGuideline = addRule;\n\tif ((hasBash || hasPowerShell) && !hasFind && !hasLs) {\n\t\tif (hasBash && hasPowerShell) {\n\t\t\taddRule(\"Use bash or PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else if (hasPowerShell) {\n\t\t\taddRule(\"Use PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else {\n\t\t\taddRule(\"Use bash for file operations like ls, rg, find\");\n\t\t}\n\t}\n\tif (shouldIncludeAskUserFallbackGuidance) {\n\t\taddGuideline(\n\t\t\t\"If an equivalent user-question tool is available, use it for all questions to the user instead of plain text, including confirmations and approvals, following its supported schema. When no usable question tool or human-input channel exists, do not stall on a question: choose the interpretation best supported by the repository and the stated objective, state the assumption in your response, and continue fully autonomously on best judgment. Tool unavailability alone is not a blocker. Preserve safety and authorization constraints.\",\n\t\t);\n\t}\n\tif (hasBash || hasPowerShell) {\n\t\taddGuideline(\n\t\t\t\"**Repository intent**: When working in a repository, infer how its maintainers actually work before imposing defaults: review recent commits, open and merged PRs, issues and their comments, and project/board status when tooling allows (for example `git log` and the `gh` CLI) to learn conventions, priorities, and scope norms. Better, identify the requesting user (`git config user.name`/`user.email`, `gh api user`) and study their own commits, PRs, reviews, and issue comments so you interpret ambiguous requests the way they would, aligning style, scope, and process with their patterns.\",\n\t\t);\n\t\taddGuideline(\n\t\t\t[\n\t\t\t\t\"**Execution history**: Leave a mineable record of how each task was executed and what the user prefers, and mine those records to calibrate later work. The records only accumulate value if every task writes them. If the user, a context file, or `APPEND_SYSTEM.md` asks you not to record some or all of these records, skip those records.\",\n\t\t\t\t\" - When you author a commit, PR, issue, or issue/review comment for a task, record how it ran: `Assistant-workflow: <workflow name> (run <runId>)` for a registered or custom workflow, or `Assistant-workflow: inline` when no workflow was used; and `Assistant-duration: <elapsed> <converged|blocked|abandoned>, estimated <estimate>` (for example `Assistant-duration: 42m converged, estimated 30m`), measuring wall-clock time from launch or task start until acceptance was proven or work stopped, including resumes and repair rounds. Take elapsed time from workflow status timing or timestamps you recorded (for example `date` at task start); write `unmeasured` rather than guess. Put these as trailers alongside `Assistant-model` in commits (git trailers, or the equivalent commit-message metadata in the repository's version control system) and as the same `Key: value` lines in PR/merge request, issue, and comment bodies. For multi-commit work, record the workflow on each commit and the final duration once, in the last commit or the PR body.\",\n\t\t\t\t\" - In the same artifacts, record how the result was verified with one `Assistant-verification: <method> <passed|failed|unavailable>: <what it proved or why>` line per method that actually ran or was attempted (for example `Assistant-verification: herdr terminal E2E passed: /tasks lists running tasks first at 80x24`, `Assistant-verification: vitest unit passed: npm run test:unit`, or `Assistant-verification: cua-driver unavailable: Accessibility permission not granted`). Name the concrete mechanism, such as unit, integration, or E2E tests, agent-browser, Cua Driver, herdr or tmux terminal automation, the qlty CLI, typecheck or lint, or a manual scenario, and the command or scenario it exercised. Record only checks that ran and their observed outcome; never record a skipped, mocked, or planned check as passed.\",\n\t\t\t\t\" - When the user states or reveals a durable preference about how they work (a correction, a rejected approach, scope, review, tooling, or communication style), record it in the same artifacts as `User-preference: <one line, in the user's terms>`, and tie it to the requesting user with a `Co-authored-by: <name> <email>` trailer taken from their version control identity (for example `git config user.name`/`user.email`) unless that line is already present; in PR, issue, and comment bodies, add the same line or their hosting account (for example from `gh api user`). Record only what the user expressed or their own edits show; never record secrets, credentials, or personal details unrelated to the work. If repository rules restrict commit or PR formats, fit the records into what they allow.\",\n\t\t\t\t\" - Before choosing between a workflow and inline work, choosing how to verify a change, estimating a duration, or interpreting an ambiguous request, mine these records with the rest of the history using the repository's version control system and its hosting CLI, for example `git log --format='%h %an <%ae> %s%n%(trailers:key=Assistant-workflow,key=Assistant-duration,key=Assistant-verification,key=User-preference,key=Co-authored-by)'` with `gh pr list --state all --search 'Assistant-workflow in:body'` on GitHub, or the equivalent commands for other systems and hosts (for example `glab` on GitLab). Compare tasks of similar kind and size, and state the sample size with the median and range. Treat fewer than five comparable records as anecdotal, and prefer the more recent record when two conflict. When choosing verification, start from the methods that proved comparable changes (the same files, subsystem, or kind of change), reuse their commands and scenarios, and do not retry a setup recorded as `unavailable` without a reason to expect a different result; past records never replace the project's required checks. Prioritize preferences tied to the requesting user by their co-author line, commit author, or hosting account. When the user has none that cover the situation, fall back to other contributors' relevant preferences as repository conventions; the user's own records and current request override them, so users can always encode their own preference. This history is a guide, not the decision: the current request, the task itself, and explicit user instructions decide between a workflow and inline work. Missing, sparse, or mostly inline workflow history is not evidence that the user prefers inline work: records exist only for tasks that wrote them, and past inline runs may reflect an earlier default rather than a choice. Without a recorded or stated preference that covers the situation, judge the task's shape yourself and choose a workflow when it would help, then let comparable records and the user's preferences refine that call.\",\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n\n\tfor (const name of selectedTools) {\n\t\tfor (const rule of toolGuidelines[name] ?? []) addRule(rule);\n\t}\n\tfor (const rule of promptGuidelines) addRule(rule);\n\taddRule(\n\t\t\"Write self-describing code and do not add comments unless the user explicitly asks for them or the task instructions call for them. Code that needs a comment to be understood is a smell: restructure it with clearer names, smaller units, or explicit types instead\",\n\t);\n\taddRule(\"Be concise in your responses\");\n\taddRule(\"Show file paths clearly when working with files\");\n\treturn rules.map((rule) => `- ${rule}`).join(\"\\n\");\n}\n\n/** Build the ordered, independently replaceable sections of the structured system prompt. */\nexport function buildSystemPromptSections(input: BuildSystemPromptOptions): SystemPromptSections {\n\tconst options = normalizeBuildSystemPromptOptions(input);\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\ttoolGuidelines,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tsections: customSections,\n\t\tcwd,\n\t\tcontextFiles,\n\t\tskills,\n\t} = options;\n\tconst explicitlyExcludedTools = new Set(options.excludedTools ?? []);\n\tconst tools = selectedTools.filter((name) => !explicitlyExcludedTools.has(name));\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\tconst modelName = options.selectedModel?.name?.trim() || options.selectedModel?.id || \"unknown\";\n\tconst modelReasoningLevel = options.selectedThinkingLevel?.trim() || \"off\";\n\tconst now = new Date();\n\tconst date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}`;\n\n\tfor (const name of Object.keys(customSections)) {\n\t\tif (!SYSTEM_PROMPT_SECTION_NAME.test(name) || name === \"preamble\") {\n\t\t\tthrow new Error(`Invalid system prompt section name: ${name}`);\n\t\t}\n\t}\n\n\tconst promptSections: Record<string, string> = {};\n\tif (customPrompt) {\n\t\tpromptSections.preamble = customPrompt;\n\t} else {\n\t\tpromptSections.preamble =\n\t\t\t\"You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\";\n\t\tconst visibleTools = tools.filter((name) => !!toolSnippets[name]);\n\t\tconst toolsList =\n\t\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join(\"\\n\") : \"(none)\";\n\t\tpromptSections.tools = `Available tools:\\n${toolsList}\\n\\nIn addition to the tools above, you may have access to other custom tools depending on the project.`;\n\t\tpromptSections.rules = `Guidelines:\\n${buildRules(tools, toolGuidelines, promptGuidelines)}`;\n\t\tpromptSections.docs = `\nAtomic documentation (read when the user asks about model choice, computer use or automation, MCP, web access, intercom, subagents, or customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)\n- Bundled integrations use the same docs root in npm and binary installations: MCP servers (docs/mcp-servers.md), web access (docs/web-access.md), intercom (docs/intercom.md), subagents (docs/subagents.md), workflows (docs/workflows.md). Read these guides rather than guessing paths inside builtin packages.\n- When the user asks which model to choose for a task, read ${docsPath}/models/model-selection.md and ${docsPath}/models/evals.md, then consult https://artificialanalysis.ai/ for the relevant benchmark charts and methodology. Match the task to individual evaluations rather than an aggregate winner. Cite the benchmark, source date, exact model/effort and cost or latency tradeoff; distinguish measured results from recommendations. If live evidence is unavailable, label the dated docs snapshot instead of claiming a refresh. Check the configured catalog before giving an exact provider/model or thinking setting; catalog presence is not proof of live access.\n- For computer use (CUA) on desktop apps, simulators and emulators, use Cua Driver through the bundled cua-driver skill and one-shot \\`cua-driver call <tool>\\` commands: when a model chooses the next action (interactive sessions or any workflow stage acting outside ctx.tool), use the CLI; when workflow TypeScript code owns the sequence and postcondition, use the @trycua/cua-driver TypeScript SDK inside ctx.tool. If \\`cua-driver --version\\` fails, make one bounded attempt with upstream's one-line executable installer and report its side effects. The executable installer does not install an agent skill; ignore upstream README's optional skill-install steps, never run \\`cua-driver skills install\\` or \\`clawhub install @cua/driver\\`, and do not link or copy a skill into \\`~/.agents/skills/cua-driver\\`. Atomic already bundles it; leave any existing user-level skill alone. Run every cua-driver command with CUA_DRIVER_RS_TELEMETRY_ENABLED=false and follow ${docsPath}/computer-use.md for install, readiness and permissions. Prefer the agent-browser skill for what it covers: websites and web apps in Chrome/Chromium, Electron desktop apps such as VS Code, Slack, Discord, Figma, Notion and Spotify, Slack workspaces, and cloud browsers. Use cua-driver for everything else (native desktop apps, iOS simulators, Android emulators, OS dialogs and permission prompts, non-Chromium browsers) and whenever agent-browser hits a limitation. For terminal automation/testing, prefer herdr on macOS, Linux and Windows; install it if missing when network access and permissions permit, and fall back to tmux or native Windows psmux if installation or use is not possible. Load the matching skill and ${docsPath}/workflows/verification.md. Preserve the pinned herdr skill's explicit-request and HERDR_ENV=1 requirements; never control a focused session from outside Herdr. Check installed capabilities, use dedicated sessions, respect desktop permissions, and stop before destructive actions. These CLIs are not interchangeable, and skills do not grant tools or authorization.\n- Also skip \\`cua-driver skills update\\` and any skill installation into other agent directories such as \\`~/.claude/skills\\`; updating the executable is separate from installing or updating a skill.\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\t}\n\n\tif (appendSystemPrompt) promptSections.addendum = appendSystemPrompt;\n\tif (contextFiles.length > 0) promptSections.project_context = renderProjectContext(contextFiles);\n\tconst skillFileReadTool = ([\"read\", \"bash\"] as const).find((tool) => tools.includes(tool));\n\tif (skillFileReadTool && skills.length > 0) {\n\t\tconst skillsPrompt = formatSkillsForPrompt(skills, skillFileReadTool).trim();\n\t\tif (skillsPrompt) promptSections.skills = skillsPrompt;\n\t}\n\tpromptSections.model = `Model name (used for commit attribution): ${modelName}\\nModel reasoning level: ${modelReasoningLevel}`;\n\tpromptSections.date = `Current date: ${date}`;\n\tpromptSections.cwd = `Current working directory: ${cwd.replace(/\\\\/g, \"/\")}`;\n\tfor (const [name, content] of Object.entries(customSections)) {\n\t\tif (content) promptSections[name] = content;\n\t}\n\n\tconst sections: SystemPromptSections = { preamble: promptSections.preamble };\n\tfor (const [name, content] of Object.entries(promptSections)) {\n\t\tif (name !== \"preamble\") sections[name] = `<${name}>\\n${content}\\n</${name}>`;\n\t}\n\treturn sections;\n}\n\n/**\n * The complete prompt state for `input`. A forced prompt is opaque and lives in `content`\n * with no sections; otherwise `content` is empty and the structured sections carry the prompt.\n */\nexport function buildSystemPromptState(input: BuildSystemPromptOptions): {\n\tcontent: string;\n\tsections?: SystemPromptSections;\n} {\n\tif (input.forceSystemPrompt !== undefined) return { content: input.forceSystemPrompt };\n\treturn { content: \"\", sections: buildSystemPromptSections(input) };\n}\n\n/** Build the system prompt text, rendered exactly as the transcript's system message replays it. */\nexport function buildSystemPrompt(input: BuildSystemPromptOptions): string {\n\treturn getSystemMessageText({ role: \"system\", ...buildSystemPromptState(input), timestamp: 0 });\n}\n\n/**\n * Diff the sections the model currently has (replayed from the transcript, so never null)\n * against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when\n * nothing changed.\n */\nexport function diffSystemPromptSections(\n\tprevious: Record<string, string | null>,\n\tcurrent: SystemPromptSections,\n): Record<string, string | null> | undefined {\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(current)) {\n\t\tif (previous[name] !== text) patch[name] = text;\n\t}\n\tfor (const name of Object.keys(previous)) {\n\t\tif (current[name] === undefined) patch[name] = null;\n\t}\n\treturn Object.keys(patch).length > 0 ? patch : undefined;\n}\n"]}
package/docs/usage.md CHANGED
@@ -173,7 +173,7 @@ User-preference: keep PRs under 500 changed lines
173
173
  Co-authored-by: Ada Lovelace <ada@example.com>
174
174
  ```
175
175
 
176
- Tasks done without a workflow record `Assistant-workflow: inline`. Each `Assistant-verification` line names one check that ran or was attempted, such as unit or E2E tests, agent-browser, Cua Driver, Herdr terminal automation, or the qlty CLI, with its outcome (`passed`, `failed`, or `unavailable`). Each preference carries a `Co-authored-by` line naming the user who expressed it. Before choosing between a workflow and inline work, deciding how to verify a change, or estimating how long a task will take, the agent looks up comparable records with your version control system and its hosting CLI (for example `git log` and `gh` on GitHub) and uses them as a guide alongside your request. For verification, it starts from the checks that proved similar changes and skips setups previously recorded as unavailable unless something has changed, while still running the project's required checks. It applies your own recorded preferences first and falls back to other contributors' preferences as repository conventions only when yours don't cover the situation, so you can always override a convention by stating your preference. To turn off any of these records, such as only preferences or all of them, say so in your request, a context file, or `APPEND_SYSTEM.md`.
176
+ Tasks done without a workflow record `Assistant-workflow: inline`. Each `Assistant-verification` line names one check that ran or was attempted, such as unit or E2E tests, agent-browser, Cua Driver, Herdr terminal automation, or the qlty CLI, with its outcome (`passed`, `failed`, or `unavailable`). Each preference carries a `Co-authored-by` line naming the user who expressed it. Before choosing between a workflow and inline work, deciding how to verify a change, or estimating how long a task will take, the agent looks up comparable records with your version control system and its hosting CLI (for example `git log` and `gh` on GitHub) and uses them as a guide alongside your request. A lack of workflow history, or a history of mostly inline tasks, does not make the agent default to inline work: it still judges from the task itself whether a workflow would help unless you have stated or recorded a preference. For verification, it starts from the checks that proved similar changes and skips setups previously recorded as unavailable unless something has changed, while still running the project's required checks. It applies your own recorded preferences first and falls back to other contributors' preferences as repository conventions only when yours don't cover the situation, so you can always override a convention by stating your preference. To turn off any of these records, such as only preferences or all of them, say so in your request, a context file, or `APPEND_SYSTEM.md`.
177
177
 
178
178
  ## Exporting and Sharing Sessions
179
179
 
@@ -496,6 +496,8 @@ a server already using that runtime. Do not delete a runtime generation,
496
496
  including a damaged one, while a managed server may still use it.
497
497
  Set `ATOMIC_POSTGRES_RUNTIME_CACHE_DIR` before starting Atomic to share retained runtime generations across separate cluster homes; only the runtime cache moves, not cluster data or ownership records. Keep this directory private to a trusted account and do not remove generations while a server may use them.
498
498
 
499
+ Atomic only uses a runtime cache whose parent folders other accounts can't write to. A folder that only its group can write to is accepted when that group is your own private group: no other account in `/etc/passwd` uses that group as its primary group, and `/etc/group` lists no member other than you. That's the default on Ubuntu and Debian, where umask 002 makes `~/.atomic` group-writable. If Atomic reports an **Untrusted embedded Postgres runtime cache directory ancestor** and falls back to in-memory workflows, run `chmod go-w` on the folder named in the message and restart Atomic.
500
+
499
501
  **Running as root on Linux.** Atomic needs an available unprivileged account, `postgres`, `nobody`, or `daemon`, because PostgreSQL cannot run as root. The cluster is stored under `/var/lib/atomic-postgres`. If privilege or runtime preparation fails, inspect the diagnostic rather than changing data ownership blindly.
500
502
 
501
503
  **Administrator accounts (Windows).** Atomic can start embedded Postgres from an elevated terminal or an administrative account without changing your account or system permissions. The server runs with reduced privileges, as it does under PostgreSQL's own launcher. Regular Windows accounts remain supported.
@@ -733,7 +735,7 @@ Set `ATOMIC_POSTGRES_RUNTIME_DIR` to a complete extracted runtime containing `bi
733
735
 
734
736
  Keep the complete extracted archive, not only the `atomic` executable. `ATOMIC_POSTGRES_RUNTIME_DIR` accepts complete legacy runtimes without provenance; an incomplete override falls through to installed candidates. Packaging failures do not require deleting or reinitializing the v18 cluster.
735
737
 
736
- If installation reports **incomplete PostgreSQL runtime**, or macOS reports a missing library such as `libzstd.1.dylib`, download a repaired release and reinstall the complete archive. A rejected installation leaves the running server untouched. Do not copy libraries from another version or delete your PostgreSQL data directory: this is an installation problem, not database corruption. An already-running server does not prove that the new installation is usable.
738
+ If starting workflows reports a missing PostgreSQL executable or library, such as `libzstd.1.dylib` on macOS, download a repaired release and reinstall the complete archive. The installers do not check the bundled PostgreSQL runtime, so the problem shows up the first time Atomic starts its embedded database. With `DBOS_SYSTEM_DATABASE_URL` set, Atomic never uses the bundled runtime. If embedded startup fails and the Docker fallback succeeds, workflows run on Docker without reporting the embedded failure. Check `~/.atomic/postgres/v18.log` if the managed database never starts. Do not copy libraries from another version or delete your PostgreSQL data directory: this is an installation problem, not database corruption. An already-running server does not prove that the new installation is usable.
737
739
 
738
740
  To check an archive runtime, set `runtime` to its `node_modules/@bastani/atomic-natives/postgres-runtime`, then run `"$runtime/bin/postgres" --version` and `"$runtime/bin/pg_ctl" --version`. On Windows use the corresponding `.exe` files in PowerShell. Both must succeed. If a library-link or copy error is reported, repair the complete installation instead of mixing libraries from different releases.
739
741
 
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@bastani/atomic",
3
- "version": "0.9.20-alpha.10",
3
+ "version": "0.9.20-alpha.11",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@bastani/atomic",
9
- "version": "0.9.20-alpha.10",
9
+ "version": "0.9.20-alpha.11",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
- "@bastani/atomic-natives": "0.9.20-alpha.10",
13
- "@bastani/pi-ai": "0.9.20-alpha.10",
12
+ "@bastani/atomic-natives": "0.9.20-alpha.11",
13
+ "@bastani/pi-ai": "0.9.20-alpha.11",
14
14
  "@dbos-inc/dbos-sdk": "4.25.14",
15
15
  "@earendil-works/pi-agent-core": "0.87.1",
16
16
  "@earendil-works/pi-client": "0.87.1",
@@ -429,18 +429,18 @@
429
429
  }
430
430
  },
431
431
  "node_modules/@bastani/atomic-natives": {
432
- "version": "0.9.20-alpha.10",
433
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives/-/atomic-natives-0.9.20-alpha.10.tgz",
432
+ "version": "0.9.20-alpha.11",
433
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives/-/atomic-natives-0.9.20-alpha.11.tgz",
434
434
  "license": "MIT",
435
435
  "optionalDependencies": {
436
- "@bastani/atomic-natives-darwin-arm64": "0.9.20-alpha.10",
437
- "@bastani/atomic-natives-darwin-x64": "0.9.20-alpha.10",
438
- "@bastani/atomic-natives-linux-arm64-gnu": "0.9.20-alpha.10",
439
- "@bastani/atomic-natives-linux-arm64-musl": "0.9.20-alpha.10",
440
- "@bastani/atomic-natives-linux-x64-gnu": "0.9.20-alpha.10",
441
- "@bastani/atomic-natives-linux-x64-musl": "0.9.20-alpha.10",
442
- "@bastani/atomic-natives-win32-arm64-msvc": "0.9.20-alpha.10",
443
- "@bastani/atomic-natives-win32-x64-msvc": "0.9.20-alpha.10"
436
+ "@bastani/atomic-natives-darwin-arm64": "0.9.20-alpha.11",
437
+ "@bastani/atomic-natives-darwin-x64": "0.9.20-alpha.11",
438
+ "@bastani/atomic-natives-linux-arm64-gnu": "0.9.20-alpha.11",
439
+ "@bastani/atomic-natives-linux-arm64-musl": "0.9.20-alpha.11",
440
+ "@bastani/atomic-natives-linux-x64-gnu": "0.9.20-alpha.11",
441
+ "@bastani/atomic-natives-linux-x64-musl": "0.9.20-alpha.11",
442
+ "@bastani/atomic-natives-win32-arm64-msvc": "0.9.20-alpha.11",
443
+ "@bastani/atomic-natives-win32-x64-msvc": "0.9.20-alpha.11"
444
444
  },
445
445
  "engines": {
446
446
  "bun": ">=1.4.2",
@@ -448,8 +448,8 @@
448
448
  }
449
449
  },
450
450
  "node_modules/@bastani/atomic-natives-darwin-arm64": {
451
- "version": "0.9.20-alpha.10",
452
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-darwin-arm64/-/atomic-natives-darwin-arm64-0.9.20-alpha.10.tgz",
451
+ "version": "0.9.20-alpha.11",
452
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-darwin-arm64/-/atomic-natives-darwin-arm64-0.9.20-alpha.11.tgz",
453
453
  "license": "MIT",
454
454
  "os": [
455
455
  "darwin"
@@ -460,8 +460,8 @@
460
460
  "optional": true
461
461
  },
462
462
  "node_modules/@bastani/atomic-natives-darwin-x64": {
463
- "version": "0.9.20-alpha.10",
464
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-darwin-x64/-/atomic-natives-darwin-x64-0.9.20-alpha.10.tgz",
463
+ "version": "0.9.20-alpha.11",
464
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-darwin-x64/-/atomic-natives-darwin-x64-0.9.20-alpha.11.tgz",
465
465
  "license": "MIT",
466
466
  "os": [
467
467
  "darwin"
@@ -472,8 +472,8 @@
472
472
  "optional": true
473
473
  },
474
474
  "node_modules/@bastani/atomic-natives-linux-arm64-gnu": {
475
- "version": "0.9.20-alpha.10",
476
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-arm64-gnu/-/atomic-natives-linux-arm64-gnu-0.9.20-alpha.10.tgz",
475
+ "version": "0.9.20-alpha.11",
476
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-arm64-gnu/-/atomic-natives-linux-arm64-gnu-0.9.20-alpha.11.tgz",
477
477
  "license": "MIT",
478
478
  "os": [
479
479
  "linux"
@@ -487,8 +487,8 @@
487
487
  "optional": true
488
488
  },
489
489
  "node_modules/@bastani/atomic-natives-linux-arm64-musl": {
490
- "version": "0.9.20-alpha.10",
491
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-arm64-musl/-/atomic-natives-linux-arm64-musl-0.9.20-alpha.10.tgz",
490
+ "version": "0.9.20-alpha.11",
491
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-arm64-musl/-/atomic-natives-linux-arm64-musl-0.9.20-alpha.11.tgz",
492
492
  "license": "MIT",
493
493
  "os": [
494
494
  "linux"
@@ -502,8 +502,8 @@
502
502
  "optional": true
503
503
  },
504
504
  "node_modules/@bastani/atomic-natives-linux-x64-gnu": {
505
- "version": "0.9.20-alpha.10",
506
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-x64-gnu/-/atomic-natives-linux-x64-gnu-0.9.20-alpha.10.tgz",
505
+ "version": "0.9.20-alpha.11",
506
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-x64-gnu/-/atomic-natives-linux-x64-gnu-0.9.20-alpha.11.tgz",
507
507
  "license": "MIT",
508
508
  "os": [
509
509
  "linux"
@@ -517,8 +517,8 @@
517
517
  "optional": true
518
518
  },
519
519
  "node_modules/@bastani/atomic-natives-linux-x64-musl": {
520
- "version": "0.9.20-alpha.10",
521
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-x64-musl/-/atomic-natives-linux-x64-musl-0.9.20-alpha.10.tgz",
520
+ "version": "0.9.20-alpha.11",
521
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-x64-musl/-/atomic-natives-linux-x64-musl-0.9.20-alpha.11.tgz",
522
522
  "license": "MIT",
523
523
  "os": [
524
524
  "linux"
@@ -532,8 +532,8 @@
532
532
  "optional": true
533
533
  },
534
534
  "node_modules/@bastani/atomic-natives-win32-arm64-msvc": {
535
- "version": "0.9.20-alpha.10",
536
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-win32-arm64-msvc/-/atomic-natives-win32-arm64-msvc-0.9.20-alpha.10.tgz",
535
+ "version": "0.9.20-alpha.11",
536
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-win32-arm64-msvc/-/atomic-natives-win32-arm64-msvc-0.9.20-alpha.11.tgz",
537
537
  "license": "MIT",
538
538
  "os": [
539
539
  "win32"
@@ -544,8 +544,8 @@
544
544
  "optional": true
545
545
  },
546
546
  "node_modules/@bastani/atomic-natives-win32-x64-msvc": {
547
- "version": "0.9.20-alpha.10",
548
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-win32-x64-msvc/-/atomic-natives-win32-x64-msvc-0.9.20-alpha.10.tgz",
547
+ "version": "0.9.20-alpha.11",
548
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-win32-x64-msvc/-/atomic-natives-win32-x64-msvc-0.9.20-alpha.11.tgz",
549
549
  "license": "MIT",
550
550
  "os": [
551
551
  "win32"
@@ -556,8 +556,8 @@
556
556
  "optional": true
557
557
  },
558
558
  "node_modules/@bastani/pi-ai": {
559
- "version": "0.9.20-alpha.10",
560
- "resolved": "https://registry.npmjs.org/@bastani/pi-ai/-/pi-ai-0.9.20-alpha.10.tgz",
559
+ "version": "0.9.20-alpha.11",
560
+ "resolved": "https://registry.npmjs.org/@bastani/pi-ai/-/pi-ai-0.9.20-alpha.11.tgz",
561
561
  "license": "MIT",
562
562
  "dependencies": {
563
563
  "@anthropic-ai/sdk": "0.124.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/atomic",
3
- "version": "0.9.20-alpha.10",
3
+ "version": "0.9.20-alpha.11",
4
4
  "description": "Atomic coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "atomicConfig": {
@@ -79,8 +79,8 @@
79
79
  "prepublishOnly": "bun run clean && bun run build && bun run shrinkwrap"
80
80
  },
81
81
  "dependencies": {
82
- "@bastani/atomic-natives": "0.9.20-alpha.10",
83
- "@bastani/pi-ai": "0.9.20-alpha.10",
82
+ "@bastani/atomic-natives": "0.9.20-alpha.11",
83
+ "@bastani/pi-ai": "0.9.20-alpha.11",
84
84
  "@dbos-inc/dbos-sdk": "4.25.14",
85
85
  "@earendil-works/pi-agent-core": "0.87.1",
86
86
  "@earendil-works/pi-client": "0.87.1",