even-keel 0.3.0 → 0.3.1

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.
Files changed (72) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1 -1
  3. package/dist/src/agent/scripted.js +32 -3
  4. package/dist/src/chain/conflict.js +41 -0
  5. package/dist/src/chain/forward.js +22 -5
  6. package/dist/src/chain/handover.js +1 -2
  7. package/dist/src/chain/maincheck.js +13 -9
  8. package/dist/src/changelog/drafts.js +4 -3
  9. package/dist/src/changelog/file.js +4 -0
  10. package/dist/src/changelog/limit.js +30 -0
  11. package/dist/src/ci/protection.js +8 -1
  12. package/dist/src/claude/adapter.js +4 -4
  13. package/dist/src/copilot/errors.js +11 -6
  14. package/dist/src/gitlab/adapter.js +1 -0
  15. package/dist/src/limits/chatgpt-seat.js +49 -0
  16. package/dist/src/limits/chatgpt.js +37 -7
  17. package/dist/src/limits/copilot.js +12 -3
  18. package/dist/src/limits/model.js +3 -0
  19. package/dist/src/limits/overage.js +6 -2
  20. package/dist/src/limits/usage.js +42 -4
  21. package/dist/src/limits/watcher.js +1 -1
  22. package/dist/src/notice/en-advice.js +2 -1
  23. package/dist/src/notice/en-values.js +2 -0
  24. package/dist/src/notice/en.js +4 -1
  25. package/dist/src/opencode/adapter.js +1 -1
  26. package/dist/src/opencode/cli.js +10 -2
  27. package/dist/src/packages/service.js +37 -0
  28. package/dist/src/profiles/model.js +1 -0
  29. package/dist/src/profiles/service.js +1 -1
  30. package/dist/src/server.js +1 -0
  31. package/dist/src/service/chain-prompts.js +13 -1
  32. package/dist/src/service/chain.js +17 -12
  33. package/dist/src/service.js +1 -1
  34. package/dist/src/storage/migrations.js +2 -0
  35. package/dist/src/storage/schema.js +1 -1
  36. package/dist/src/tools/panel.js +7 -9
  37. package/dist/src/tools/projectSettings.js +60 -0
  38. package/dist/src/tools/sessionSettings.js +11 -4
  39. package/dist/web/assets/{BadgeDialog-B8RUL_Ow.js → BadgeDialog-D4hwGrta.js} +1 -1
  40. package/dist/web/assets/{DescriptionEditor-DUSwRGCZ.js → DescriptionEditor-ujHSJeis.js} +1 -1
  41. package/dist/web/assets/{ProjectPackages-BJEPijBV.js → ProjectPackages-DMk8vL5N.js} +1 -1
  42. package/dist/web/assets/{Select-NXi_Bsw-.js → Select-BMRSXvrD.js} +1 -1
  43. package/dist/web/assets/{TaskCard-DeP8bF9-.js → TaskCard-DeZtmpq4.js} +2 -2
  44. package/dist/web/assets/TranscriptWindow-DRGnlese.css +1 -0
  45. package/dist/web/assets/{TranscriptWindow-DVoHtE_o.js → TranscriptWindow-hQHw_CQ7.js} +1 -1
  46. package/dist/web/assets/{accountParts-CNUeXPYn.js → accountParts-B-b8vNCY.js} +1 -1
  47. package/dist/web/assets/blocks-BTQTnJ34.js +12 -0
  48. package/dist/web/assets/{cardDrafts-CyzO-ro7.js → cardDrafts-yo2X_Uq1.js} +1 -1
  49. package/dist/web/assets/{cardSide-CSmytank.js → cardSide-Y3dIjNVW.js} +1 -1
  50. package/dist/web/assets/feedLine-BJhjgpoe.js +1 -0
  51. package/dist/web/assets/{hooks-CgKVeUg8.js → hooks-CDqQcVnS.js} +1 -1
  52. package/dist/web/assets/index-B9H7kxbk.js +25 -0
  53. package/dist/web/assets/index-gsaRwWJo.css +1 -0
  54. package/dist/web/assets/{lib-DnFFmOv9.js → lib-DUH5hYcn.js} +1 -1
  55. package/dist/web/assets/overview-BdakxI-5.js +7 -0
  56. package/dist/web/assets/packageGroups-D15r6pKX.js +1 -0
  57. package/dist/web/assets/{react-dom-DiYkIXNS.js → react-dom-CDxcrI4x.js} +1 -1
  58. package/dist/web/assets/{rules-DLe7kZM5.js → rules-CVcjwHXa.js} +1 -1
  59. package/dist/web/assets/{useFileDrop-CEn6qZnh.js → useFileDrop-vzFQ_b-5.js} +1 -1
  60. package/dist/web/assets/{useHeightGlide-BPjzH9PL.js → useHeightGlide-DBfdeOiD.js} +1 -1
  61. package/dist/web/assets/useRowFocus-CMvgf7Aw.js +1 -0
  62. package/dist/web/index.html +15 -15
  63. package/even-keel.config.example.json +1 -1
  64. package/package.json +1 -1
  65. package/dist/web/assets/TranscriptWindow-BN6jSpev.css +0 -1
  66. package/dist/web/assets/blocks-CiOz7u_W.js +0 -12
  67. package/dist/web/assets/feedLine-txivfLQO.js +0 -1
  68. package/dist/web/assets/index-BT7ooY-T.js +0 -25
  69. package/dist/web/assets/index-hTYDOTAZ.css +0 -1
  70. package/dist/web/assets/overview-0NAogPYB.js +0 -7
  71. package/dist/web/assets/packageGroups-6mYiV3fk.js +0 -1
  72. package/dist/web/assets/useRowFocus-COI8llTH.js +0 -1
@@ -10,7 +10,7 @@ const SKIPPED_QUOTA = 'completions';
10
10
  * The monthly allowance of a Copilot answer (BTN-341): the first limited `quota_snapshots` entry — premium requests, else
11
11
  * another one such as AI credits — or the free plan's `limited_user_quotas.chat` out of `monthly_quotas.chat`, as one
12
12
  * month window that counts what is left. AI credits without `remaining` use `entitlement - credits_used`.
13
- * `unlimited` — every quota is; `no-quota` — the provider gives no allowance; `undefined` — nothing readable.
13
+ * `unlimited` — every quota is, by a flag nothing contradicts (`spentDespiteFlag`); `no-quota` — the provider gives no allowance; `undefined` — nothing readable.
14
14
  */
15
15
  export function copilotLimits(body, at) {
16
16
  if (!isRecord(body))
@@ -23,13 +23,14 @@ export function copilotLimits(body, at) {
23
23
  (premium.token_based_billing === true && !(nonnegative(premium.entitlement) && premium.entitlement > 0))))
24
24
  return 'no-quota';
25
25
  const quotas = Object.entries(snapshots).filter((entry) => entry[0] !== SKIPPED_QUOTA && isRecord(entry[1]));
26
- const limited = quotas.filter(([, quota]) => quota.unlimited !== true).sort(([a], [b]) => Number(b === PREFERRED_QUOTA) - Number(a === PREFERRED_QUOTA));
26
+ const limited = quotas.filter(([, quota]) => quota.unlimited !== true || spentDespiteFlag(quota))
27
+ .sort(([a], [b]) => Number(b === PREFERRED_QUOTA) - Number(a === PREFERRED_QUOTA));
27
28
  for (const [, quota] of limited) {
28
29
  if (quota.has_quota === false)
29
30
  continue;
30
31
  const left = quota.remaining === undefined && nonnegative(quota.entitlement) && nonnegative(quota.credits_used)
31
32
  ? Math.max(0, quota.entitlement - quota.credits_used) : quota.remaining;
32
- const window = counted(quota.entitlement, left, resetsAt);
33
+ const window = spentDespiteFlag(quota) ? { usedPercentage: 100, resetsAt, left: 0 } : counted(quota.entitlement, left, resetsAt);
33
34
  if (window !== undefined) {
34
35
  const overage = copilotOverage(quota, at);
35
36
  return { ...monthOnly(window, at), ...(overage !== undefined && { overage }) };
@@ -124,6 +125,14 @@ function get(url, authorization, timeoutMs, fetchImpl) {
124
125
  const headers = { Authorization: authorization, Accept: 'application/json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'even-keel' };
125
126
  return fetchImpl(url, { headers, signal: AbortSignal.timeout(timeoutMs) });
126
127
  }
128
+ /**
129
+ * `unlimited: true` that the quota itself contradicts (EKR-133): nothing left or no allowance, something spent and no
130
+ * overage. A spent Business seat answers so; the same shape with overage permitted stays unlimited.
131
+ */
132
+ function spentDespiteFlag(quota) {
133
+ return quota.unlimited === true && (quota.remaining === 0 || quota.entitlement === 0) &&
134
+ nonnegative(quota.credits_used) && quota.credits_used > 0 && quota.overage_permitted === false;
135
+ }
127
136
  function counted(total, left, resetsAt) {
128
137
  if (!nonnegative(total) || !nonnegative(left) || !(total > 0))
129
138
  return undefined;
@@ -99,12 +99,15 @@ export function newestLimits(a, b) {
99
99
  if (a === undefined || b === undefined)
100
100
  return a ?? b;
101
101
  const latest = Date.parse(b.updatedAt) > Date.parse(a.updatedAt) ? b : a;
102
+ const older = latest === a ? b : a;
102
103
  const extra = newer(a.overage, b.overage);
103
104
  const models = newer(a.models, b.models);
105
+ const seat = latest.spendCap === undefined && older.spendCap !== undefined;
104
106
  return {
105
107
  ...latest,
106
108
  ...(extra !== undefined && { overage: extra }),
107
109
  ...(models !== undefined && { models }),
110
+ ...(seat && { spendCap: older.spendCap, ...(latest.month === undefined && older.month !== undefined && { month: older.month }) }),
108
111
  };
109
112
  }
110
113
  /** Of two parts with their own time, the newer one, or whichever is there. */
@@ -42,7 +42,7 @@ export function usingOverage(entry, now) {
42
42
  return extra.using === true;
43
43
  if (extra.source !== 'chatgpt' || !['codex', 'opencode'].includes(entry.agent) || !(extra.available || extra.unlimited))
44
44
  return false;
45
- return [entry.limits?.fiveHour, entry.limits?.sevenDay, entry.limits?.month]
45
+ return [entry.limits?.fiveHour, entry.limits?.sevenDay, chatGptPlanMonth(entry.limits)]
46
46
  .some((window) => window != null && window.usedPercentage >= 100 && Date.parse(window.resetsAt) > now.getTime());
47
47
  }
48
48
  /** Fresh evidence for the chain's stop policy; the returned time identifies the provider reading, not a receipt. */
@@ -66,12 +66,16 @@ export function overageLimit(entry, now) {
66
66
  return null;
67
67
  const at = Date.parse(extra.updatedAt) < Date.parse(limits.updatedAt) ? extra.updatedAt : limits.updatedAt;
68
68
  if (extra.source === 'chatgpt' && ['codex', 'opencode'].includes(entry.agent) && (extra.available === true || extra.unlimited === true) &&
69
- [limits.fiveHour, limits.sevenDay, limits.month ?? null].some(exhausted))
69
+ [limits.fiveHour, limits.sevenDay, chatGptPlanMonth(limits)].some(exhausted))
70
70
  return { at, source: 'chatgpt' };
71
71
  if (extra.source === 'github-quota' && ['copilot', 'opencode'].includes(entry.agent) && extra.enabled === true && exhausted(limits.month ?? null))
72
72
  return { at, source: 'github-quota' };
73
73
  return null;
74
74
  }
75
+ /** The month a spent allowance of a ChatGPT plan can run on into credits: a seat's month is its credit cap itself (EKR-132). */
76
+ function chatGptPlanMonth(limits) {
77
+ return limits?.spendCap === undefined ? (limits?.month ?? null) : null;
78
+ }
75
79
  function isRecord(value) {
76
80
  return typeof value === 'object' && value !== null && !Array.isArray(value);
77
81
  }
@@ -17,12 +17,44 @@ export function parseUsage(stdout, at) {
17
17
  const body = messages.findLast((message) => isRecord(message) && message.type === 'result') ?? (messages.length === 1 ? messages[0] : undefined);
18
18
  if (!isRecord(body))
19
19
  return { kind: 'unknown', reason: notice('usage.notObject', {}) };
20
- const answer = parseResult(body, at);
20
+ const rows = usageRows(messages);
21
+ const answer = spentOrFailed(body) ?? planWindowsOf(rows, at) ?? parseResult(body, at);
21
22
  if (answer.kind !== 'limits')
22
23
  return answer;
23
- const weeks = modelWeeksOf(usageRows(messages));
24
+ const weeks = modelWeeksOf(rows);
24
25
  return weeks === undefined ? answer : { kind: 'limits', limits: { ...answer.limits, models: { weeks, updatedAt: at } } };
25
26
  }
27
+ /**
28
+ * The plan's windows from the rows of a usage answer (EKR-131): the `session` row is the five hours, `weekly_all` the
29
+ * all-models week, and a plan without one has no such row — a verified Ultra no `session`, a Team seat no `weekly_all`.
30
+ * Every row counts, whatever its `is_active`: that marks the one limit holding the account now, not the ones that apply.
31
+ * `undefined` — neither row, or one a window cannot be made of, so the text decides.
32
+ */
33
+ function planWindowsOf(rows, at) {
34
+ if (!Array.isArray(rows))
35
+ return undefined;
36
+ const rowOf = (kind) => rows.find((row) => isRecord(row) && row.kind === kind);
37
+ const session = rowOf('session');
38
+ const week = rowOf('weekly_all');
39
+ if (session === undefined && week === undefined)
40
+ return undefined;
41
+ const fiveHour = session === undefined ? null : rowWindowOf(session);
42
+ const sevenDay = week === undefined ? null : rowWindowOf(week);
43
+ if (fiveHour === undefined || sevenDay === undefined)
44
+ return undefined;
45
+ const absent = [...(session === undefined ? ['fiveHour'] : []), ...(week === undefined ? ['sevenDay'] : [])];
46
+ return { kind: 'limits', limits: { fiveHour, sevenDay, ...(absent.length > 0 && { absent }), updatedAt: at, source: 'usage' } };
47
+ }
48
+ /** A row's window; `null` — unused and without a reset, so not started; `undefined` — no window can be made of it. */
49
+ function rowWindowOf(row) {
50
+ const { percent, resets_at: resets } = row;
51
+ if (typeof percent !== 'number' || !Number.isFinite(percent))
52
+ return undefined;
53
+ const reset = typeof resets === 'string' ? Date.parse(resets) : Number.NaN;
54
+ if (!Number.isNaN(reset))
55
+ return { usedPercentage: percent, resetsAt: new Date(reset).toISOString() };
56
+ return percent === 0 && (resets === null || resets === undefined) ? null : undefined;
57
+ }
26
58
  /**
27
59
  * The models' own weeks among the rows of a usage answer: `usage_report.rate_limits.limits[]` of the CLI's `/usage`
28
60
  * message, the same rows as `limits[]` of `/api/oauth/usage` (`test/fixtures/limits/`). A row is classified by its
@@ -67,14 +99,20 @@ function usageRows(messages) {
67
99
  }
68
100
  return undefined;
69
101
  }
70
- function parseResult(body, at) {
71
- const { num_turns: turns, total_cost_usd: cost, is_error: failed, result } = body;
102
+ /** An answer that took a model turn, cost money or failed; `undefined` — a clean local answer. */
103
+ function spentOrFailed(body) {
104
+ const { num_turns: turns, total_cost_usd: cost, is_error: failed } = body;
72
105
  if (turns !== 0)
73
106
  return { kind: 'spent', reason: notice('usage.turns', { value: JSON.stringify(turns) ?? 'missing' }) };
74
107
  if (cost !== 0)
75
108
  return { kind: 'spent', reason: notice('usage.cost', { value: JSON.stringify(cost) ?? 'missing' }) };
76
109
  if (failed !== false)
77
110
  return { kind: 'unknown', reason: notice('usage.isError', {}) };
111
+ return undefined;
112
+ }
113
+ /** The plan's windows from the text of the `result`: the way for an answer without the rows. */
114
+ function parseResult(body, at) {
115
+ const { result } = body;
78
116
  if (typeof result !== 'string')
79
117
  return { kind: 'unknown', reason: notice('usage.noResult', {}) };
80
118
  if (SUBSCRIPTION_LINE.test(result) && !LIMIT_LINE.test(result))
@@ -207,7 +207,7 @@ export class LimitsWatcher {
207
207
  else {
208
208
  // A fallback (Codex reads its rollouts when ChatGPT does not answer) may be older than the last poll.
209
209
  account.polled = newestLimits(answer.limits, account.polled);
210
- setHealth(account, 'ok', null, at);
210
+ setHealth(account, 'ok', answer.reason ?? null, at);
211
211
  }
212
212
  }
213
213
  /** A polled account that no poll has answered since the start. */
@@ -8,7 +8,8 @@ export const ADVICE = {
8
8
  'chain.unchangedNotCompleted': () => 'move it there yourself and resume the chain, or skip the task',
9
9
  'review.notOpened': () => 'fix access and press Resume, answer its session from the chat, or skip the task',
10
10
  'review.notCompleted': () => 'move it there yourself and resume the chain, or skip the task',
11
- 'review.noNote': (p) => (p.reason === undefined ? undefined : 'write a safe note in the task folder, mark again and press Resume'),
11
+ // The mark is the session's and its new one opens the pull request with no Resume, which only rereads the same path (EKR-118).
12
+ 'review.noNote': (p) => (p.reason === undefined ? undefined : 'answer its session from the chat to write it under .temp/ and mark again: the chain goes on by itself'),
12
13
  'review.noBranch': () => "check out the task's branch there and press Resume, or skip the task",
13
14
  'review.dirty': () => 'commit or remove them and press Resume, answer its session from the chat, or skip the task',
14
15
  'review.notReady': () => 'fix that and the chain goes on by itself within a minute, or turn PR mode off',
@@ -3,6 +3,8 @@ export const FORGES = { github: 'GitHub', forgejo: 'Forgejo', gitlab: 'GitLab' }
3
3
  export const PROVIDER_NAMES = { anthropic: 'Anthropic', openai: 'OpenAI', openrouter: 'OpenRouter', github: 'GitHub' };
4
4
  /** The agents of the account folders by their registry name, as their adapters' `title`. */
5
5
  export const AGENT_NAMES = { claude: 'Claude Code', codex: 'Codex', opencode: 'OpenCode', copilot: 'GitHub Copilot', demo: 'Demo' };
6
+ /** The limit windows of an account as a message names them. */
7
+ export const SPENT_WINDOWS = { fiveHour: '5-hour', sevenDay: 'weekly', month: 'monthly' };
6
8
  export const list = (items) => items.join(', ');
7
9
  /** The service's user and home in brackets, when known (`cloudErrorNotice`). */
8
10
  export const whose = (p) => (p.user === '' ? '' : ` (${p.user}, ${p.home})`);
@@ -1,5 +1,5 @@
1
1
  import { STARTUP_NOTICES } from './en-startup.js';
2
- import { AGENT_NAMES, BUILTIN_FIELDS, FORGES, GIT_STEPS, MODELS_NAMED, MOVE_LABELS, PROVIDER_NAMES, UPDATE_BLOCKS, list, megabytes, sizeShown, whose } from './en-values.js';
2
+ import { AGENT_NAMES, BUILTIN_FIELDS, FORGES, GIT_STEPS, MODELS_NAMED, MOVE_LABELS, PROVIDER_NAMES, SPENT_WINDOWS, UPDATE_BLOCKS, list, megabytes, sizeShown, whose } from './en-values.js';
3
3
  export { AGENT_NAMES, FORGES, MODELS_NAMED, PROVIDER_NAMES, megabytes, sizeShown, whose } from './en-values.js';
4
4
  // The English texts of the server's messages: the log and the English page both read them.
5
5
  import { REVIEW_NOTICES } from './en-review.js';
@@ -222,6 +222,7 @@ export const en = {
222
222
  'copilot.startFailed': (p) => `copilot: could not start ${p.task} in ${p.cwd}`,
223
223
  'copilot.binaryMissing': (p) => `Copilot CLI could not be started: “${p.bin}” is not a program Even Keel can run`,
224
224
  'copilot.modelUnavailable': (p) => `Copilot cannot use the model “${p.model}”. Choose an available model in Model in the project's session settings (or change the model on the task’s card, under “Runs on”), then choose “New session”.`,
225
+ 'copilot.apiUnreachable': () => 'Copilot could not reach the Copilot API to load its models. Check the network of Even Keel’s machine and, behind a proxy, HTTPS_PROXY in its environment, then choose “New session”.',
225
226
  'copilot.notSignedIn': () => 'Copilot is not signed in on this machine. Run “gh auth login” as the user Even Keel runs as, or add a Copilot account with its own token on the Accounts page, then choose “New session”.',
226
227
  'copilot.resumeFailed': (p) => `copilot: could not resume ${p.task} in ${p.cwd}`,
227
228
  'copilot.unknownSession': (p) => `copilot: Even Keel did not start the session ${p.session}`,
@@ -326,6 +327,7 @@ export const en = {
326
327
  'usage.chatGptExpired': () => "the ChatGPT sign-in's access token expired; start a session or renew the account's sign-in",
327
328
  'usage.chatGptRevoked': () => "the ChatGPT sign-in was revoked, for example after a plan change; renew the account's sign-in",
328
329
  'usage.chatGptUnread': () => "ChatGPT's usage answer has no readable limit windows",
330
+ 'usage.chatGptSpendCap': () => "This seat's monthly credit limit in the workspace is spent; the account waits for the next month. Ask the workspace owner to raise it, or pick another account for the project.",
329
331
  'usage.openCodeNone': () => "no ChatGPT, Copilot or Go subscription: OpenCode's free models and other API keys have no limits to read",
330
332
  'usage.goKeyExpired': () => 'The OpenCode Go key expired or was revoked. Create a new key in OpenCode Console and use “Replace key”.',
331
333
  'account.goKeyRejected': () => 'OpenCode Console refused this key. Create a new key in OpenCode Console and try again.',
@@ -362,6 +364,7 @@ export const en = {
362
364
  'changelog.empty': (p) => `changelog: ${p.milestone} has no done task to write a draft from`,
363
365
  'changelog.noAgent': (p) => `changelog: the agent of the account ${p.project} runs on cannot write a draft`,
364
366
  'changelog.failed': (p) => `changelog: the agent did not write the draft of ${p.project}`,
367
+ 'changelog.limitSpent': (p) => `changelog: the ${p.window === undefined ? 'usage' : SPENT_WINDOWS[p.window]} limit of the account “${p.account}” is spent${p.until === undefined ? '' : ` until ${p.until}`}, the draft is not written. Wait for the reset or choose another account for the project under Project settings → Sessions.`,
365
368
  'changelog.unnoticed': (p) => `changelog: the agent found nothing a user would notice in the done tasks of ${p.milestone} (${list(p.tasks)}), so the section has no entry`,
366
369
  'changelog.noDraft': (p) => `changelog: ${p.milestone} has no draft yet`,
367
370
  'changelog.released': (p) => `changelog: the section of ${p.milestone} is released as ${p.tag} and is not changed`,
@@ -16,7 +16,7 @@ import { readCatalogue } from './window.js';
16
16
  import { filterChatGptModels } from './models.js';
17
17
  const HISTORY_FEED = 5_000;
18
18
  /** The version the README's "Before you run it" names; raised after the live run of each release (`docs/releases.md`). */
19
- const CHECKED = '1.19.5';
19
+ const CHECKED = '1.19.6';
20
20
  /**
21
21
  * OpenCode through `opencode run --format json`: a turn is a detached process, as Codex's is; a session lives between
22
22
  * turns in Even Keel's registry and the account's `opencode.db` (`docs/sessions/opencode.md`). The account is a folder of the
@@ -34,10 +34,17 @@ export const LOG_SILENCE_MS = 30_000;
34
34
  const STREAM_ERROR_EVENT = 'even_keel_stream_error';
35
35
  /**
36
36
  * Chain sessions run without a human: OpenCode's tools are allowed by default and an `ask` is rejected on its own in
37
- * `run`, so the session never hangs on one. A merge into the main checkout from a worktree is `external_directory`,
37
+ * `run`, so the session never hangs on one. A rejected `ask` ends the turn unless `CONTINUE_ON_DENY` is set, which
38
+ * every config of Even Keel's turns carries. A merge into the main checkout from a worktree is `external_directory`,
38
39
  * which is allowed for chain sessions (`sessionConfig`).
39
40
  */
40
41
  export const SESSION_MODE = 'default';
42
+ /**
43
+ * A rejected `ask` (OpenCode's default `read` rules ask for `*.env` and `*.env.*`) and a dismissed question end the
44
+ * turn without it: the session would stand waiting with no question (EKR-119). With it the model gets the rejection
45
+ * as the tool's error and goes on. A Protection `deny` never ends the turn either way.
46
+ */
47
+ const CONTINUE_ON_DENY = { experimental: { continue_loop_on_deny: true } };
41
48
  /** The sign-ins the page offers, as `opencode providers login` takes them through a pipe (BTN-214). */
42
49
  export const LOGIN_METHODS = {
43
50
  chatgpt: ['-p', 'openai', '-m', 'ChatGPT Pro/Plus (headless)'],
@@ -100,7 +107,7 @@ export function sessionConfig(start, projectServers, skillDirs, plugins = [], wi
100
107
  ...(rules.bash.length > 0 ? { bash: Object.fromEntries(rules.bash.map(pattern => [pattern, 'deny'])) } : {}),
101
108
  ...Object.fromEntries(rules.tools.map(tool => [tool, 'deny'])),
102
109
  };
103
- const config = { $schema: 'https://opencode.ai/config.json', permission, disabled_providers: ['github-copilot'] };
110
+ const config = { $schema: 'https://opencode.ai/config.json', permission, disabled_providers: ['github-copilot'], ...CONTINUE_ON_DENY };
104
111
  if (start.mcp !== undefined) {
105
112
  const own = Object.fromEntries(projectServers.map((name) => [name, { enabled: false }]));
106
113
  const gateway = Object.fromEntries(start.mcp.map((server) => [gatewayName(server), { type: 'remote', url: server.url, enabled: true }]));
@@ -149,6 +156,7 @@ export function writeConfig(projectServers) {
149
156
  $schema: 'https://opencode.ai/config.json',
150
157
  disabled_providers: ['github-copilot'],
151
158
  permission: Object.fromEntries(WRITE_DENIED.map((tool) => [tool, 'deny'])),
159
+ ...CONTINUE_ON_DENY,
152
160
  };
153
161
  if (projectServers.length > 0)
154
162
  config.mcp = Object.fromEntries(projectServers.map((name) => [name, { enabled: false }]));
@@ -337,6 +337,41 @@ export class Packages {
337
337
  this.notes.set(name, install === null ? notice('packages.upToDate', { name }) : changed > 0 ? notice('packages.updatedDependencies', { name, version, changed }) : notice('packages.updated', { name, version }));
338
338
  this.deps.onChange();
339
339
  }
340
+ /**
341
+ * Check all of the catalog: every fetched marketplace of an installed plugin is fetched again, once each, and the
342
+ * page shows the newer versions; nothing is installed — that is Update. Every marketplace is tried, the first failure thrown.
343
+ */
344
+ async checkAll() {
345
+ const fetched = new Set();
346
+ for (const [name, record] of Object.entries(this.file.packages)) {
347
+ if (record.plugin === undefined || record.removed === true || current(record) === undefined)
348
+ continue;
349
+ try {
350
+ if (FETCHED.has(locatePlugin(this.deps.globalDir, record.plugin.name, record.plugin.marketplace, this.local).kind))
351
+ fetched.add(record.plugin.marketplace);
352
+ }
353
+ catch {
354
+ this.deps.log(`packages: ${name}: its marketplace is not found, not checked`);
355
+ }
356
+ }
357
+ let first;
358
+ for (const marketplace of fetched) {
359
+ try {
360
+ await this.deps.updateMarketplace(marketplace);
361
+ }
362
+ catch (error) {
363
+ this.deps.log(`packages: the marketplace ${marketplace} not fetched: ${error.message}`);
364
+ first ??= fail('packages.marketplaceUpdate', { marketplace }, { detail: error.message }, { cause: error });
365
+ }
366
+ }
367
+ if (this.wrapsSkills())
368
+ this.rewrap();
369
+ this.plugins = undefined;
370
+ this.offers = undefined;
371
+ this.deps.onChange();
372
+ if (first !== undefined)
373
+ throw first;
374
+ }
340
375
  remove(name) {
341
376
  this.notBuiltIn(name);
342
377
  this.recordOf(name).removed = true;
@@ -544,6 +579,8 @@ export class Packages {
544
579
  version ??= Object.values(planned).find((each) => each.npm !== null)?.npm ?? null;
545
580
  const last = current(record);
546
581
  const scripts = record.scripts === true;
582
+ // The offer is read again from the folder just copied: one cached before it would show Update over the new install.
583
+ this.offers?.byName.delete(name);
547
584
  if (last !== undefined && last.version === version && sameServers(last.servers, planned) && (last.scripts === true) === scripts) {
548
585
  rmSync(home, { recursive: true, force: true });
549
586
  return null;
@@ -11,6 +11,7 @@ export function profileKinds(trackers, cis = {}) {
11
11
  title: adapter.title,
12
12
  variables: adapter.variables,
13
13
  hostVariables: adapter.hostVariables,
14
+ ...(adapter.optionalVariables === undefined ? {} : { optionalVariables: adapter.optionalVariables }),
14
15
  ...(adapter.alternatives === undefined ? {} : { alternatives: adapter.alternatives }),
15
16
  help: adapter.help,
16
17
  ...(adapter.mcpKeys === undefined ? {} : { mcpKeys: adapter.mcpKeys }),
@@ -119,7 +119,7 @@ export class Profiles {
119
119
  kind,
120
120
  title: each.title,
121
121
  tracker: each.projects !== undefined,
122
- fields: each.variables.map((name) => ({ name, secret: isSecret(name) })),
122
+ fields: each.variables.map((name) => ({ name, secret: isSecret(name), ...(each.optionalVariables?.includes(name) === true ? { optional: true } : {}) })),
123
123
  hostVariables: [...each.hostVariables],
124
124
  alternatives: (each.alternatives ?? []).map((names) => [...names]),
125
125
  help: each.help,
@@ -109,6 +109,7 @@ const COMMANDS = {
109
109
  'account/cancel': ({ account }) => account.cancel(),
110
110
  'packages/install': ({ packages }, body) => packages.install(nameOf(body)),
111
111
  'packages/update': ({ packages }, body) => packages.update(nameOf(body)),
112
+ 'packages/check': ({ packages }) => packages.checkAll(),
112
113
  'packages/remove': ({ packages }, body) => packages.remove(nameOf(body)),
113
114
  'packages/marketplace': ({ packages }) => packages.addMarketplace(),
114
115
  'packages/plugin': ({ packages }, body) => packages.addPlugin(textOf(body.plugin, 'plugin'), textOf(body.marketplace, 'marketplace'), optionalProjectOf(body)),
@@ -3,6 +3,7 @@ import { join } from 'node:path';
3
3
  import { withBrief, withPrompts, withTracker, withUnbriefed, withVocabulary } from '../chain/relay.js';
4
4
  import { ChangelogDrafts } from '../changelog/drafts.js';
5
5
  import { DEFAULT_CHANGELOG } from '../changelog/file.js';
6
+ import { limitRefusalIn, spentLimitOf } from '../changelog/limit.js';
6
7
  import { idPrefixOf, isPlain, projectLabel } from '../config.js';
7
8
  import { commitChangelog } from '../git/changelog.js';
8
9
  import { runGit } from '../git/run.js';
@@ -27,6 +28,11 @@ export function wireChangelogs(ctx) {
27
28
  const agent = ctx.agentOf(home);
28
29
  if (agent.write === undefined)
29
30
  throw fail('changelog.noAgent', { project });
31
+ const known = spentLimitOf(ctx.limits.limits(home.key), new Date());
32
+ if (known !== null) {
33
+ console.log(`changelog: ${project} draft not sent, the ${known.window ?? 'usage'} limit of ${home.key} is spent until ${known.until ?? 'unknown'}`);
34
+ throw fail('changelog.limitSpent', { account: home.key, ...known });
35
+ }
30
36
  console.log(`changelog: ${project} writes a draft on ${home.key}`);
31
37
  try {
32
38
  const { text, spend } = await agent.write(home, { cwd: ctx.configStore.current.projects[project], prompt, model, timeoutMs: ctx.CHANGELOG_TIMEOUT_MS });
@@ -34,7 +40,13 @@ export function wireChangelogs(ctx) {
34
40
  return { text, spend: { ...spend, account: home.key } };
35
41
  }
36
42
  catch (error) {
37
- throw fail('changelog.failed', { project }, { detail: error instanceof Error ? error.message : String(error) }, { cause: error });
43
+ const detail = error instanceof Error ? error.message : String(error);
44
+ const refused = limitRefusalIn(detail);
45
+ if (refused === null)
46
+ throw fail('changelog.failed', { project }, { detail }, { cause: error });
47
+ console.log(`changelog: ${project} draft refused on the limit of ${home.key}: ${detail}`);
48
+ const until = spentLimitOf(ctx.limits.limits(home.key), new Date())?.until;
49
+ throw fail('changelog.limitSpent', { account: home.key, ...refused, ...(until !== undefined && { until }) });
38
50
  }
39
51
  },
40
52
  file: async (project) => {
@@ -1,7 +1,8 @@
1
1
  export { wireChangelogs, wireBriefed, wireWithProject } from './chain-prompts.js';
2
2
  import { deferLeftFolder, midTurn } from './cleanup.js';
3
3
  export { deferLeftFolder, STOP_RETRY_MS, stopLingering, stopTaskSessions } from './cleanup.js';
4
- import { mkdir } from 'node:fs/promises';
4
+ import { mkdir, readFile } from 'node:fs/promises';
5
+ import { join } from 'node:path';
5
6
  import { accountAt } from '../account/ledger.js';
6
7
  import { accountId, launchBlock } from '../account/model.js';
7
8
  import { sessionBase } from '../agent/env.js';
@@ -130,7 +131,7 @@ export function wireKeepWarm(ctx) {
130
131
  if (view === undefined || session === undefined)
131
132
  throw new Error(`the session ${sessionId} is not live`);
132
133
  const home = ctx.homeOf(session.account);
133
- const start = { name: task, cwd: session.cwd, prompt: KEEP_WARM_PROMPT, model: view.model, settings: ctx.settingsFor(task), ...ctx.agentExtras(home, ctx.projectOf(task), task) };
134
+ const start = { name: task, cwd: session.cwd, prompt: KEEP_WARM_PROMPT, model: view.model, settings: await ctx.settingsFor(task), ...ctx.agentExtras(home, ctx.projectOf(task), task) };
134
135
  return ctx.agentOf(home).warm(home, session, start);
135
136
  },
136
137
  now: () => new Date(),
@@ -152,7 +153,7 @@ export async function wireDispatcher(ctx) {
152
153
  const started = ctx.withProject(await ctx.briefed(task, startPrompt(task, place, ctx.promptLanguage(project), ctx.branchOf(project), ctx.pullRequestsOn(project), !isPlain(ctx.configStore.current, project)), project), project);
153
154
  const { prompt, model, provider, fallback } = ctx.planFor(task, extra === undefined ? started : `${started}\n${extra}\n`, project);
154
155
  const extras = ctx.agentExtras(home, project, task);
155
- const sessionId = await ctx.launchIn(home, { name: task, cwd: place.path, prompt, model, settings: ctx.settingsFor(task, project), ...extras }, project);
156
+ const sessionId = await ctx.launchIn(home, { name: task, cwd: place.path, prompt, model, settings: await ctx.settingsFor(task, project), ...extras }, project);
156
157
  if (fallback === null)
157
158
  return { sessionId };
158
159
  console.warn(englishOf(ctx.noAccountFor(task, fallback, provider)));
@@ -282,7 +283,7 @@ export async function wireDispatcher(ctx) {
282
283
  const note = await readNote(notePath);
283
284
  const at = new Date().toISOString();
284
285
  const extras = ctx.agentExtras(home, project, task);
285
- const sessionId = await ctx.launchIn(home, { name: task, cwd: session.workdir, prompt, model, settings: ctx.settingsFor(task, project), ...extras }, project);
286
+ const sessionId = await ctx.launchIn(home, { name: task, cwd: session.workdir, prompt, model, settings: await ctx.settingsFor(task, project), ...extras }, project);
286
287
  const snapshot = { at, task, sessionId, previous: session.sessionId, reason: snapshotReason(reason), prompt, notePath, note };
287
288
  ctx.writes.add(`the handoff snapshot of ${task}`, saveSnapshot(ctx.db, snapshot));
288
289
  return sessionId;
@@ -294,7 +295,7 @@ export async function wireDispatcher(ctx) {
294
295
  const text = fixPrompt(report, place, ctx.promptLanguage(project), ctx.branchOf(project), reran === true);
295
296
  const { prompt, model } = ctx.planFor(name, ctx.withProject(text, project), project);
296
297
  const extras = ctx.agentExtras(home, project, name);
297
- return ctx.launchIn(home, { name, cwd: place.path, prompt, model, settings: ctx.settingsFor(name, project), ...extras }, project);
298
+ return ctx.launchIn(home, { name, cwd: place.path, prompt, model, settings: await ctx.settingsFor(name, project), ...extras }, project);
298
299
  },
299
300
  launchCarry: async (project, name, report) => {
300
301
  const home = ctx.homeOf(ctx.choiceFor(project).account);
@@ -302,7 +303,7 @@ export async function wireDispatcher(ctx) {
302
303
  const place = await ctx.places.ready(project, name);
303
304
  const { prompt, model } = ctx.planFor(name, ctx.withProject(carryPrompt(report, place, ctx.promptLanguage(project), ctx.branchOf(project)), project), project);
304
305
  const extras = ctx.agentExtras(home, project, name);
305
- return ctx.launchIn(home, { name, cwd: place.path, prompt, model, settings: ctx.settingsFor(name, project), ...extras }, project);
306
+ return ctx.launchIn(home, { name, cwd: place.path, prompt, model, settings: await ctx.settingsFor(name, project), ...extras }, project);
306
307
  },
307
308
  carried: async (project, commit) => (await runGit(ctx.configStore.current.projects[project], ['merge-base', '--is-ancestor', commit, `refs/heads/${ctx.branchOf(project)}`])).code === 0,
308
309
  stop: async (session) => {
@@ -442,11 +443,12 @@ export function wireForwards(ctx) {
442
443
  return chainQuiet(ctx.dispatcher.state.active.find((chain) => chain.project === project), (task) => status(task) === 'busy' || status(task) === 'waiting');
443
444
  },
444
445
  git: runGit,
446
+ read: (repo, path) => readFile(join(repo, path), 'utf8').catch(() => null),
445
447
  sync: ctx.syncProject,
446
448
  now: () => new Date(),
447
449
  changed: () => ctx.hub.broadcastSoon('state', ctx.getState),
448
450
  log: (message) => console.log(message),
449
- carrying: (from) => ctx.dispatcher.carrying(from)?.task ?? null,
451
+ carrying: (from) => ctx.dispatcher.carrying(from) ?? null,
450
452
  auto: (from) => ctx.configStore.current.settings[from]?.carryAgent === true || ctx.configStore.current.unattended,
451
453
  resolve: async (from, ask) => {
452
454
  const config = ctx.configStore.current;
@@ -462,7 +464,10 @@ export function wireForwards(ctx) {
462
464
  output: ask.output,
463
465
  });
464
466
  const at = new Date().toISOString();
465
- ctx.dispatcher.carry(from, { task: carryNameOf(config.keys, from), into: ask.into, at, commit: ask.commit, commits: ask.commits, report });
467
+ const carry = { task: carryNameOf(config.keys, from), into: ask.into, at, commit: ask.commit, commits: ask.commits, report };
468
+ if (ask.conflict !== undefined)
469
+ carry.conflict = ask.conflict;
470
+ ctx.dispatcher.carry(from, carry);
466
471
  },
467
472
  });
468
473
  }
@@ -471,7 +476,7 @@ export function resumeWith(ctx, task, session, prompt) {
471
476
  if (ctx.approved(task, session, prompt))
472
477
  return session.sessionId;
473
478
  const home = ctx.homeOf(session.account);
474
- const start = ctx.goOnWith(home, task, session, prompt);
479
+ const start = await ctx.goOnWith(home, task, session, prompt);
475
480
  const went = session.stopped || ctx.liveView(task)?.hungSince != null ? undefined : await ctx.agentOf(home).reply?.(home, session, start);
476
481
  if (went != null)
477
482
  return went;
@@ -498,14 +503,14 @@ export function approved(ctx, task, session, prompt) {
498
503
  console.log(`sessions: ${task}: the user ${move.kind === 'allow' ? 'allowed' : 'denied'} the call the session ${session.sessionId} waited to have approved`);
499
504
  return true;
500
505
  }
501
- export function goOnWith(ctx, home, task, session, prompt) {
506
+ export async function goOnWith(ctx, home, task, session, prompt) {
502
507
  const { model } = ctx.planFor(task, prompt);
503
508
  const extras = ctx.agentExtras(home, ctx.projectOf(task), task);
504
- return { name: task, cwd: session.cwd, prompt, model, settings: ctx.settingsFor(task), ...extras };
509
+ return { name: task, cwd: session.cwd, prompt, model, settings: await ctx.settingsFor(task), ...extras };
505
510
  }
506
511
  export async function steer(ctx, task, session, prompt) {
507
512
  const home = ctx.homeOf(session.account);
508
- return (await ctx.agentOf(home).reply?.(home, session, ctx.goOnWith(home, task, session, prompt))) != null;
513
+ return (await ctx.agentOf(home).reply?.(home, session, await ctx.goOnWith(home, task, session, prompt))) != null;
509
514
  }
510
515
  export function occupantsOf(ctx, slot, task) {
511
516
  const owners = new Map(ctx.launches.map((entry) => [entry.sessionId, entry.task]));
@@ -735,7 +735,7 @@ const trackerPlace = (reader) => {
735
735
  const briefed = chainService.wireBriefed(context);
736
736
  /** Even Keel's prompt and the project's own, for a new session only: a resumed one already has them. */
737
737
  const withProject = chainService.wireWithProject(context);
738
- const settingsFor = createSessionSettings({ config: () => configStore.current, packages, globalDir: homes.global.dir, trim: () => dispatcher.state.trimTools, projectOf });
738
+ const settingsFor = createSessionSettings({ config: () => configStore.current, packages, globalDir: homes.global.dir, trim: () => dispatcher.state.trimTools, projectOf, git: runGit, branchOf });
739
739
  function projectOf(task) { return chainService.projectOf(context, task); }
740
740
  const slotsSeen = new Map();
741
741
  /** How many slots the project's tasks may be in: the most it had since the start, so a pool shrunk on the fly still finds its busy slots. */
@@ -152,6 +152,8 @@ export function currentConfig(raw, active = GLOBAL_ACCOUNT) {
152
152
  // seen yet, so only the version changes.
153
153
  // v33 → v34: a project's optional `milestoneOrder` (BTN-792); omitted keeps the automatic order, so only the version changes.
154
154
  // v34 → v35: a project's optional `badge` (BTN-915); omitted means no badge is pushed, so only the version changes.
155
+ // v39 → v40: the optional `conflict` of a carry session in `state/chain.json` (`ci[<project>].carry`, EKR-135); omitted
156
+ // means the page shows dashes for the conflict, so only the version changes.
155
157
  const feeds = version < 23 ? feedsRuled(sdk) : sdk;
156
158
  const trusted = version < 26 ? automaticTrust(feeds) : feeds;
157
159
  const kept = version < 28 ? manualKept(trusted) : trusted;
@@ -4,7 +4,7 @@ import { fail } from '../notice/notice.js';
4
4
  * file's format is a new version, a step in `migrations.ts` and a new frozen sample in `test/fixtures/schema-v<N>/`.
5
5
  * A future import into a database reads it to know what it imports.
6
6
  */
7
- export const SCHEMA_VERSION = 39;
7
+ export const SCHEMA_VERSION = 40;
8
8
  /** A file without a version is from before versions: 1. */
9
9
  export function versionOf(raw) {
10
10
  const version = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? raw.version : undefined;
@@ -9,6 +9,7 @@ import { parseCodexRules } from '../codex/rules.js';
9
9
  import { samePath } from '../paths.js';
10
10
  import { protectionRules } from '../sessions/protection.js';
11
11
  import { projectDirName } from '../sessions/paths.js';
12
+ import { readProjectSettings } from './projectSettings.js';
12
13
  import { latestStarted, readReceived, skillSource } from './received.js';
13
14
  import { accountDrift, forPackageOff, settingRows, trimSettings } from './settings.js';
14
15
  /** Tool attachments come in the first lines; MCP servers connect a little after the first answer. */
@@ -23,7 +24,7 @@ const RECENT = 8;
23
24
  * blanked in `env`, the ban on git of a project without it (`noGit`) with the CLI's worktree guard off and, with trimming on, the trimming. The flag's `env` outranks the user's and the project's settings,
24
25
  * and an empty value hides a key one of them sets (checked on CLI 2.1.310, BTN-436).
25
26
  */
26
- export function chainSettings(repo, plugins, trim, hidden, globalDir, cacheTtl, secrets = [], protection, autoCompactWindow = null, noGit = false) {
27
+ export function chainSettings(repo, plugins, trim, hidden, globalDir, cacheTtl, secrets = [], protection, autoCompactWindow = null, noGit = false, files = { project: undefined, local: undefined }) {
27
28
  const always = {
28
29
  permissions: { deny: protectionRules(protection, [], undefined, undefined, noGit).claude },
29
30
  autoMemoryDirectory: sharedMemory(globalDir, repo),
@@ -37,14 +38,11 @@ export function chainSettings(repo, plugins, trim, hidden, globalDir, cacheTtl,
37
38
  };
38
39
  if (!trim)
39
40
  return JSON.stringify(always);
40
- const { project, local } = projectSettings(repo);
41
- return JSON.stringify({ ...trimSettings(hidden, project, local), ...always });
41
+ return JSON.stringify({ ...trimSettings(hidden, files.project, files.local), ...always });
42
42
  }
43
43
  export async function readToolsView(project, places) {
44
44
  const { repo } = places;
45
45
  const user = readJson(join(places.globalDir, 'settings.json'));
46
- const { project: shared, local } = projectSettings(repo);
47
- const chain = places.trim ? trimSettings(places.hidden, shared, local) : undefined;
48
46
  const configs = places.configs.map(readJson).filter((config) => config !== undefined);
49
47
  const localAllowed = configs.flatMap((config) => {
50
48
  const entries = Object.entries(objectOf(config.projects)).filter(([path]) => samePath(path, repo));
@@ -56,12 +54,14 @@ export async function readToolsView(project, places) {
56
54
  .filter((drift) => drift.keys.length > 0);
57
55
  const plain = places.plain === true;
58
56
  const files = plain ? folderFiles(repo) : [];
59
- const [received, rules, docs, codexProject] = await Promise.all([
57
+ const [{ project: shared, local, drift }, received, rules, docs, codexProject] = await Promise.all([
58
+ readProjectSettings(places.git, repo, places.branch, plain),
60
59
  readNewest(places.homes, repo),
61
60
  plain ? repoRulesOf(files) : readRepoRules(places.git, repo, places.branch),
62
61
  plain ? files.filter(isDoc).sort() : readBranchDocs(places.git, repo, places.branch),
63
62
  plain ? readFolderCodexRules(join(repo, CODEX_RULES)) : readBranchCodexRules(places.git, repo, places.branch),
64
63
  ]);
64
+ const chain = places.trim ? trimSettings(places.hidden, shared, local) : undefined;
65
65
  const codexUser = places.codexHome === undefined ? [] : readFolderCodexRules(join(places.codexHome, 'rules'));
66
66
  const known = { user: new Set(dirNames(join(places.globalDir, 'skills'))), project: new Set(dirNames(join(repo, '.claude', 'skills'))) };
67
67
  return {
@@ -73,6 +73,7 @@ export async function readToolsView(project, places) {
73
73
  received: received === undefined ? null : { ...received, skills: received.skills.map((name) => ({ name, source: skillSource(name, known) })) },
74
74
  rules,
75
75
  docs,
76
+ ...(drift !== undefined && { settingsDrift: drift }),
76
77
  ...(plain ? { plain: true } : {}),
77
78
  };
78
79
  }
@@ -144,9 +145,6 @@ function readFolderCodexRules(dir) {
144
145
  function isOwnRulesFile(file) {
145
146
  return file.endsWith('.rules') && !file.endsWith(PROTECTION_FILE);
146
147
  }
147
- function projectSettings(repo) {
148
- return { project: readJson(join(repo, '.claude', 'settings.json')), local: readJson(join(repo, '.claude', 'settings.local.json')) };
149
- }
150
148
  /** The project's session that started last among the last touched transcripts, worktree ones first: chain sessions run there. */
151
149
  async function readNewest(homes, repo) {
152
150
  const base = projectDirName(repo).toLowerCase();