even-keel 0.3.0 → 0.3.2

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 (84) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +3 -3
  3. package/dist/src/agent/scripted.js +32 -3
  4. package/dist/src/badge/collect.js +26 -4
  5. package/dist/src/badge/render.js +2 -1
  6. package/dist/src/chain/conflict.js +41 -0
  7. package/dist/src/chain/forward.js +22 -5
  8. package/dist/src/chain/handover.js +1 -2
  9. package/dist/src/chain/maincheck.js +13 -9
  10. package/dist/src/changelog/drafts.js +4 -3
  11. package/dist/src/changelog/file.js +4 -0
  12. package/dist/src/changelog/limit.js +30 -0
  13. package/dist/src/ci/protection.js +8 -1
  14. package/dist/src/claude/adapter.js +4 -4
  15. package/dist/src/claude/sdk/host.js +10 -3
  16. package/dist/src/copilot/adapter.js +1 -1
  17. package/dist/src/copilot/errors.js +11 -6
  18. package/dist/src/gitlab/adapter.js +1 -0
  19. package/dist/src/limits/chatgpt-seat.js +49 -0
  20. package/dist/src/limits/chatgpt.js +37 -7
  21. package/dist/src/limits/copilot.js +12 -3
  22. package/dist/src/limits/model.js +3 -0
  23. package/dist/src/limits/overage.js +6 -2
  24. package/dist/src/limits/usage.js +42 -4
  25. package/dist/src/limits/watcher.js +1 -1
  26. package/dist/src/notice/en-advice.js +2 -1
  27. package/dist/src/notice/en-values.js +2 -0
  28. package/dist/src/notice/en.js +5 -1
  29. package/dist/src/opencode/adapter.js +1 -1
  30. package/dist/src/opencode/cli.js +10 -2
  31. package/dist/src/packages/service.js +37 -0
  32. package/dist/src/profiles/model.js +1 -0
  33. package/dist/src/profiles/service.js +1 -1
  34. package/dist/src/server.js +1 -0
  35. package/dist/src/service/chain-prompts.js +13 -1
  36. package/dist/src/service/chain.js +17 -12
  37. package/dist/src/service/trackers.js +3 -2
  38. package/dist/src/service.js +1 -1
  39. package/dist/src/sessions/ask.js +6 -0
  40. package/dist/src/sessions/monitor.js +1 -0
  41. package/dist/src/sessions/permission.js +3 -2
  42. package/dist/src/sessions/transcript.js +29 -2
  43. package/dist/src/storage/migrations.js +2 -0
  44. package/dist/src/storage/schema.js +1 -1
  45. package/dist/src/tools/panel.js +7 -9
  46. package/dist/src/tools/projectSettings.js +60 -0
  47. package/dist/src/tools/sessionSettings.js +11 -4
  48. package/dist/src/tracker/questions.js +35 -3
  49. package/dist/web/assets/{BadgeDialog-B8RUL_Ow.js → BadgeDialog-DTnQXw9H.js} +1 -1
  50. package/dist/web/assets/{DescriptionEditor-DUSwRGCZ.js → DescriptionEditor-CpRmzCRQ.js} +1 -1
  51. package/dist/web/assets/{ProjectPackages-BJEPijBV.js → ProjectPackages-BILdF91o.js} +1 -1
  52. package/dist/web/assets/{Select-NXi_Bsw-.js → Select-BkfVMQn9.js} +1 -1
  53. package/dist/web/assets/{TaskCard-DeP8bF9-.js → TaskCard-BdMTPm5U.js} +2 -2
  54. package/dist/web/assets/TranscriptWindow-BNF7AkTM.css +1 -0
  55. package/dist/web/assets/TranscriptWindow-DWmiEsux.js +4 -0
  56. package/dist/web/assets/{accountParts-CNUeXPYn.js → accountParts-BgNHNRlI.js} +1 -1
  57. package/dist/web/assets/blocks-CrABcaPz.js +12 -0
  58. package/dist/web/assets/{cardDrafts-CyzO-ro7.js → cardDrafts-BfmbAV1M.js} +1 -1
  59. package/dist/web/assets/{cardSide-CSmytank.js → cardSide-D2KI5tvT.js} +1 -1
  60. package/dist/web/assets/feedLine-Ba2zSS8M.js +1 -0
  61. package/dist/web/assets/{hooks-CgKVeUg8.js → hooks-JRdbz0x_.js} +1 -1
  62. package/dist/web/assets/index-CLtOpp9i.js +25 -0
  63. package/dist/web/assets/index-gsaRwWJo.css +1 -0
  64. package/dist/web/assets/{lib-DnFFmOv9.js → lib-BWXVCBDM.js} +1 -1
  65. package/dist/web/assets/overview-D3YlvCUL.js +7 -0
  66. package/dist/web/assets/packageGroups-Bp5E3IBW.js +1 -0
  67. package/dist/web/assets/{react-dom-DiYkIXNS.js → react-dom-BrsVbrva.js} +1 -1
  68. package/dist/web/assets/{rules-DLe7kZM5.js → rules-LK65q0Fp.js} +1 -1
  69. package/dist/web/assets/{useFileDrop-CEn6qZnh.js → useFileDrop-uBrD_n1G.js} +1 -1
  70. package/dist/web/assets/{useHeightGlide-BPjzH9PL.js → useHeightGlide-DUlst5w-.js} +1 -1
  71. package/dist/web/assets/useRowFocus-B25YUpUj.js +1 -0
  72. package/dist/web/index.html +15 -15
  73. package/even-keel.config.example.json +1 -1
  74. package/package.json +2 -2
  75. package/tally/tally.config.json +8 -0
  76. package/dist/web/assets/TranscriptWindow-BN6jSpev.css +0 -1
  77. package/dist/web/assets/TranscriptWindow-DVoHtE_o.js +0 -4
  78. package/dist/web/assets/blocks-CiOz7u_W.js +0 -12
  79. package/dist/web/assets/feedLine-txivfLQO.js +0 -1
  80. package/dist/web/assets/index-BT7ooY-T.js +0 -25
  81. package/dist/web/assets/index-hTYDOTAZ.css +0 -1
  82. package/dist/web/assets/overview-0NAogPYB.js +0 -7
  83. package/dist/web/assets/packageGroups-6mYiV3fk.js +0 -1
  84. package/dist/web/assets/useRowFocus-COI8llTH.js +0 -1
@@ -6,6 +6,7 @@ export const gitlab = {
6
6
  title: 'GitLab',
7
7
  variables: [GITLAB_URL, GITLAB_TOKEN],
8
8
  hostVariables: [GITLAB_URL],
9
+ optionalVariables: [GITLAB_URL],
9
10
  help: 'https://docs.gitlab.com/user/profile/personal_access_tokens/',
10
11
  mcpServer: 'gitlab',
11
12
  editsTasks: true,
@@ -0,0 +1,49 @@
1
+ /** Plans a person buys for themselves: a workspace seat (Team, Business, Edu, Enterprise) is any other. */
2
+ const PERSONAL_PLANS = new Set(['free', 'go', 'plus', 'pro']);
3
+ /**
4
+ * Where ChatGPT's spend page reads a workspace seat's monthly credits (EKR-132): the owner's cap and what the seat used
5
+ * this month. `wham/usage` has neither; Codex does not ask it.
6
+ */
7
+ export function chatGptSeatUsageUrl(accountId) {
8
+ return `https://chatgpt.com/backend-api/accounts/${encodeURIComponent(accountId)}/spend-controls/current-user/monthly-usage?supports_usage_limit_modes=true`;
9
+ }
10
+ /** Whether `wham/usage` is a workspace seat's: it has `spend_control` and the plan is not a personal one. */
11
+ export function isChatGptSeat(body) {
12
+ return isRecord(body) && isRecord(body.spend_control) && typeof body.plan_type === 'string' && !PERSONAL_PLANS.has(body.plan_type);
13
+ }
14
+ /** `spend_control.reached` of `wham/usage`: the seat's monthly cap is spent; `undefined` — the answer does not say. */
15
+ export function spendCapReached(body) {
16
+ const control = isRecord(body) ? body.spend_control : undefined;
17
+ return isRecord(control) && typeof control.reached === 'boolean' ? control.reached : undefined;
18
+ }
19
+ /**
20
+ * The seat's month out of the `monthly-usage` answer: the credits used of the cap, resetting at the next calendar month
21
+ * in UTC (no reset is named; none other seen yet). Whether the seat is closed is `spend_control.reached`'s to say, so
22
+ * the count alone stays under 100 %, and `reached` makes it 100 %. `undefined` — not an answer in credits.
23
+ */
24
+ export function seatMonth(raw, at, reached) {
25
+ if (!isRecord(raw) || (raw.balance_unit !== undefined && raw.balance_unit !== 'credit'))
26
+ return undefined;
27
+ const used = raw.current_month_usage;
28
+ if (typeof used !== 'number' || !Number.isFinite(used) || used < 0)
29
+ return undefined;
30
+ const resetsAt = nextMonth(at);
31
+ const cap = isRecord(raw.effective_monthly_limit) ? raw.effective_monthly_limit : undefined;
32
+ const limit = cap?.limit;
33
+ if (typeof limit !== 'number' || !Number.isFinite(limit) || limit <= 0 || (cap?.limit_mode !== undefined && cap.limit_mode !== 'amount_credits')) {
34
+ return { usedPercentage: reached ? 100 : 0, resetsAt, used };
35
+ }
36
+ const share = Math.round((used / limit) * 1000) / 10;
37
+ return { usedPercentage: reached ? 100 : Math.min(share, 99), resetsAt, used, limit };
38
+ }
39
+ /** A reached cap with no count read: the month is spent until it turns. */
40
+ export function spentSeatMonth(at) {
41
+ return { usedPercentage: 100, resetsAt: nextMonth(at) };
42
+ }
43
+ function nextMonth(at) {
44
+ const now = new Date(at);
45
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)).toISOString();
46
+ }
47
+ function isRecord(value) {
48
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
49
+ }
@@ -1,5 +1,6 @@
1
1
  import { notice } from '../notice/notice.js';
2
2
  import { chatGptCredits } from './overage.js';
3
+ import { chatGptSeatUsageUrl, isChatGptSeat, seatMonth, spendCapReached, spentSeatMonth } from './chatgpt-seat.js';
3
4
  /** What Codex's `/status` asks: the windows of the ChatGPT subscription, shared by every client signed in to it. */
4
5
  export const CHATGPT_USAGE_URL = 'https://chatgpt.com/backend-api/wham/usage';
5
6
  const AUTH_CLAIM = 'https://api.openai.com/auth';
@@ -12,30 +13,43 @@ const polls = new Map();
12
13
  * The windows of ChatGPT's usage answer (BTN-341): `rate_limit.primary_window`/`secondary_window`, each with the share
13
14
  * used, its length and its reset in seconds — the five-hour, the weekly and the free plan's 30-day window by their length,
14
15
  * as Codex's rollouts (`limitsOfRollout`). `undefined` — the answer holds no window.
16
+ *
17
+ * A workspace seat's monthly credit cap (EKR-132): `spend_control.reached` closes the account (`open: false`, the month
18
+ * spent), and `monthly`, the seat's `monthly-usage` answer, gives the month's count (`seatMonth`).
15
19
  */
16
- export function chatGptLimits(body, at) {
20
+ export function chatGptLimits(body, at, monthly) {
17
21
  const limit = isRecord(body) ? body.rate_limit : undefined;
18
22
  const overage = chatGptCredits(isRecord(body) ? body.credits : undefined, at);
19
23
  const windows = isRecord(limit) ? [limit.primary_window, limit.secondary_window].filter(isRecord) : [];
20
- if (windows.length === 0 && overage === undefined)
24
+ const reached = spendCapReached(body);
25
+ const seat = isChatGptSeat(body);
26
+ if (windows.length === 0 && overage === undefined && !seat && reached !== true)
21
27
  return undefined;
22
28
  const of = (minutes) => {
23
29
  const found = windows.find((window) => window.limit_window_seconds === minutes * 60);
24
30
  return found === undefined ? null : windowOf(found, at);
25
31
  };
26
- const monthly = windows.some((window) => window.limit_window_seconds === MONTH * 60);
27
32
  const flags = isRecord(limit) && (typeof limit.allowed === 'boolean' || typeof limit.limit_reached === 'boolean') ? limit : undefined;
28
- const open = flags === undefined ? undefined : flags.allowed === true && flags.limit_reached === false;
33
+ const allowed = flags === undefined ? undefined : flags.allowed === true && flags.limit_reached === false;
34
+ const open = reached === true ? false : allowed;
35
+ const month = monthOf(windows.some((window) => window.limit_window_seconds === MONTH * 60) ? of(MONTH) : undefined, seat && monthly !== undefined ? seatMonth(monthly, at, reached === true) : undefined, reached === true, at);
29
36
  return {
30
37
  fiveHour: of(FIVE_HOURS),
31
38
  sevenDay: of(WEEK),
32
- ...(monthly ? { month: of(MONTH) } : {}),
39
+ ...(month !== undefined ? { month } : {}),
33
40
  updatedAt: at,
34
41
  source: 'api',
35
42
  ...(overage !== undefined && { overage }),
36
43
  ...(open !== undefined && { open }),
44
+ ...((seat || reached === true) && { spendCap: { reached: reached === true, updatedAt: at } }),
37
45
  };
38
46
  }
47
+ /** The plan's own 30 days first; else the seat's credits; a reached cap spends whichever there is, or a month of its own. */
48
+ function monthOf(plan, seat, reached, at) {
49
+ if (plan !== undefined)
50
+ return reached && plan !== null ? { ...plan, usedPercentage: 100 } : plan;
51
+ return seat ?? (reached ? spentSeatMonth(at) : undefined);
52
+ }
39
53
  /** The ChatGPT account an access token is for, by its claim; `null` — not a token that says. */
40
54
  export function chatGptAccountOf(token) {
41
55
  const auth = claimsOf(token)?.[AUTH_CLAIM];
@@ -125,10 +139,26 @@ export async function askChatGpt(signIn, at, timeoutMs, fetchImpl = fetch) {
125
139
  return { kind: 'missing', reason: notice('usage.chatGptRevoked', {}) };
126
140
  if (!response.ok)
127
141
  throw new Error(`ChatGPT usage answered ${response.status}`);
128
- const limits = chatGptLimits(await response.json().catch(() => undefined), at);
142
+ const body = await response.json().catch(() => undefined);
143
+ const monthly = accountId !== null && isChatGptSeat(body) ? await askSeatMonth(accountId, headers, timeoutMs, fetchImpl) : undefined;
144
+ const limits = chatGptLimits(body, at, monthly);
129
145
  if (limits === undefined)
130
146
  return { kind: 'unknown', reason: notice('usage.chatGptUnread', {}) };
131
- return { kind: 'limits', limits: accountId === null ? limits : { ...limits, pool: chatGptPool(accountId) } };
147
+ return {
148
+ kind: 'limits',
149
+ limits: accountId === null ? limits : { ...limits, pool: chatGptPool(accountId) },
150
+ ...(limits.spendCap?.reached === true && { reason: notice('usage.chatGptSpendCap', {}) }),
151
+ };
152
+ }
153
+ /** The seat's `monthly-usage` answer; `undefined` on any refusal or failure — a seat without the count, not an error. */
154
+ async function askSeatMonth(accountId, headers, timeoutMs, fetchImpl) {
155
+ try {
156
+ const response = await fetchImpl(chatGptSeatUsageUrl(accountId), { headers, signal: AbortSignal.timeout(timeoutMs) });
157
+ return response.ok ? await response.json() : undefined;
158
+ }
159
+ catch {
160
+ return undefined;
161
+ }
132
162
  }
133
163
  /** The pool of a ChatGPT account: a Codex and an OpenCode folder signed in to it share its limits. */
134
164
  export function chatGptPool(accountId) {
@@ -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';
@@ -44,6 +44,7 @@ export const en = {
44
44
  'chain.limitsUnread': (p) => `Waiting for the first answer about the limits of the account ${p.account}: without it a spent limit looks free.${p.next === undefined ? '' : ` The next poll is at ${p.next}.`}`,
45
45
  'chain.limitSpent': (p) => `chain: The usage limit is spent until ${p.until}${p.account === undefined ? '' : ` on ${p.provider ?? ''} account “${p.account}”`}. Wait for the reset, change the account in the project's pool under Project settings → Sessions, or the provider on the task's card.`,
46
46
  'session.transient': () => 'waiting to retry',
47
+ 'session.approvalExpired': (p) => `The question about the ${p.tool} call is closed: the CLI stopped waiting for an answer and refused the call itself, it did not run. The session goes on without it.`,
47
48
  'session.transientRetry': (p) => `The model is temporarily unavailable. The dispatcher will retry this same session at ${p.at}. You can continue it now from the chat or start a new session.`,
48
49
  'chain.noSession': (p) => `chain: no session of ${p.task} is known`,
49
50
  'chain.noAccountFor': (p) => `chain: the run of ${p.task} is set to ${p.label}, but no account of that provider is in the pool; it runs on ${p.provider}, as its project does`,
@@ -222,6 +223,7 @@ export const en = {
222
223
  'copilot.startFailed': (p) => `copilot: could not start ${p.task} in ${p.cwd}`,
223
224
  'copilot.binaryMissing': (p) => `Copilot CLI could not be started: “${p.bin}” is not a program Even Keel can run`,
224
225
  '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”.`,
226
+ '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
227
  '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
228
  'copilot.resumeFailed': (p) => `copilot: could not resume ${p.task} in ${p.cwd}`,
227
229
  'copilot.unknownSession': (p) => `copilot: Even Keel did not start the session ${p.session}`,
@@ -326,6 +328,7 @@ export const en = {
326
328
  'usage.chatGptExpired': () => "the ChatGPT sign-in's access token expired; start a session or renew the account's sign-in",
327
329
  'usage.chatGptRevoked': () => "the ChatGPT sign-in was revoked, for example after a plan change; renew the account's sign-in",
328
330
  'usage.chatGptUnread': () => "ChatGPT's usage answer has no readable limit windows",
331
+ '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
332
  'usage.openCodeNone': () => "no ChatGPT, Copilot or Go subscription: OpenCode's free models and other API keys have no limits to read",
330
333
  'usage.goKeyExpired': () => 'The OpenCode Go key expired or was revoked. Create a new key in OpenCode Console and use “Replace key”.',
331
334
  'account.goKeyRejected': () => 'OpenCode Console refused this key. Create a new key in OpenCode Console and try again.',
@@ -362,6 +365,7 @@ export const en = {
362
365
  'changelog.empty': (p) => `changelog: ${p.milestone} has no done task to write a draft from`,
363
366
  'changelog.noAgent': (p) => `changelog: the agent of the account ${p.project} runs on cannot write a draft`,
364
367
  'changelog.failed': (p) => `changelog: the agent did not write the draft of ${p.project}`,
368
+ '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
369
  '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
370
  'changelog.noDraft': (p) => `changelog: ${p.milestone} has no draft yet`,
367
371
  '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) => {