@cruxy/cli 0.29.0 → 0.29.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,52 @@
1
+ import type { Usage } from "@cruxy/sdk";
2
+ import type { LoopBudget } from "./loop.js";
3
+ /**
4
+ * The live budget primitive for the agent loop: iteration + token + optional
5
+ * wall-clock caps, checked by {@link runAgent} before every model turn (see
6
+ * `LoopBudget`). A tripped cap stops the run with a human-readable reason and
7
+ * the coherent partial history — the loop never runs unbounded.
8
+ *
9
+ * It lives beside the loop it guards: the loop defines the `LoopBudget` seam,
10
+ * this is its one concrete implementation, and the subagent orchestrator, the
11
+ * job manager, and {@link Session} (per-turn token guard) all consume it.
12
+ */
13
+ /**
14
+ * Hard caps a run executes under. `maxTokens` is always finite; `maxIterations`
15
+ * is finite for a subagent (bounded by construction) but may be
16
+ * `Number.POSITIVE_INFINITY` for a token-only guard where iteration count is
17
+ * bounded elsewhere (a main turn is already capped by `agent.maxIterations` in
18
+ * the loop). `timeoutMs` is an optional wall-clock backstop on top.
19
+ */
20
+ export interface BudgetLimits {
21
+ /** Cap on the run's model turns (may be `Infinity` for a token-only guard). */
22
+ maxIterations: number;
23
+ /** Cap on the run's combined input+output tokens. */
24
+ maxTokens: number;
25
+ /** Optional wall-clock cap in milliseconds. */
26
+ timeoutMs?: number;
27
+ }
28
+ /**
29
+ * Resolve the effective limits for one spawn: start from the configured
30
+ * ceilings and let overrides only *narrow* them. A request above a ceiling is
31
+ * clamped down, not honored — "budget overrides within limits" by construction.
32
+ */
33
+ export declare function resolveBudget(defaults: BudgetLimits, overrides?: Partial<BudgetLimits>): BudgetLimits;
34
+ /**
35
+ * A live budget for one run. The wall clock starts at construction (spawn /
36
+ * turn start); the clock source is injectable so tests never sleep.
37
+ */
38
+ export declare class Budget implements LoopBudget {
39
+ private readonly limits;
40
+ private readonly now;
41
+ private readonly startedAt;
42
+ constructor(limits: BudgetLimits, now?: () => number);
43
+ /**
44
+ * The reason to stop before the next model turn, or `null` to continue.
45
+ * Checked at iteration boundaries — the in-flight turn always completes, so
46
+ * overshoot is bounded by one turn.
47
+ */
48
+ exceeded(state: {
49
+ iterations: number;
50
+ usage: Usage;
51
+ }): string | null;
52
+ }
@@ -1,9 +1,3 @@
1
- /**
2
- * The subagent budget (C.14): iteration + token + optional wall-clock caps,
3
- * checked by the agent loop before every model turn (see `LoopBudget`). A
4
- * tripped cap stops the run with a human-readable reason — the subagent
5
- * returns a partial result, it never runs unbounded.
6
- */
7
1
  /**
8
2
  * Resolve the effective limits for one spawn: start from the configured
9
3
  * ceilings and let overrides only *narrow* them. A request above a ceiling is
@@ -23,8 +17,8 @@ export function resolveBudget(defaults, overrides) {
23
17
  };
24
18
  }
25
19
  /**
26
- * A live budget for one subagent run. The wall clock starts at construction
27
- * (spawn time); the clock source is injectable so tests never sleep.
20
+ * A live budget for one run. The wall clock starts at construction (spawn /
21
+ * turn start); the clock source is injectable so tests never sleep.
28
22
  */
29
23
  export class Budget {
30
24
  limits;
@@ -103,6 +103,21 @@ export interface RunAgentArgs {
103
103
  * is kill-tree'd rather than orphaned.
104
104
  */
105
105
  signal?: AbortSignal;
106
+ /**
107
+ * Mid-loop compaction seam (build item 3). Called at the top of every
108
+ * iteration with the running history; returns the history to continue from —
109
+ * unchanged when under threshold, or with its older prefix summarized away
110
+ * when over. Supplied by {@link Session}, which reuses its own
111
+ * threshold/cut/summarize machinery, so the loop gains no summarization
112
+ * knowledge and no logic is duplicated. Omitted → history is never compacted
113
+ * mid-loop (unchanged behavior; subagents pass nothing).
114
+ *
115
+ * This is what keeps a long autonomous turn — where `send` compacts only once
116
+ * up front and never again — within the context window: without it a run that
117
+ * drives dozens of tool calls (each result appended, some tens of KB) grows
118
+ * unbounded until the next `send`, which in one-shot never comes.
119
+ */
120
+ compact?: (messages: Message[]) => Promise<Message[]>;
106
121
  }
107
122
  /**
108
123
  * The budget seam for {@link runAgent}: implementations track their own caps
@@ -40,8 +40,9 @@ async function driveLoop(args, renderer, routed) {
40
40
  const { provider, registry, config, ctx } = args;
41
41
  const { logger } = ctx;
42
42
  // Work on a copy so we never mutate the caller's array as a side effect; the
43
- // extended history is returned for the caller to adopt.
44
- const messages = [...args.messages];
43
+ // extended history is returned for the caller to adopt. Reassigned wholesale
44
+ // when the mid-loop compaction seam folds away an older prefix.
45
+ let messages = [...args.messages];
45
46
  const usage = { input_tokens: 0, output_tokens: 0 };
46
47
  const maxIterations = config.agent.maxIterations;
47
48
  // The tool catalogue and environment are stable across the loop, so build the
@@ -88,6 +89,14 @@ async function driveLoop(args, renderer, routed) {
88
89
  usage,
89
90
  };
90
91
  }
92
+ // Mid-loop compaction (build item 3), after the abort/budget checks so a
93
+ // cancelled or over-budget run never spends a summary call: fold away the
94
+ // older prefix when the history has grown past threshold *this* iteration.
95
+ // The seam preserves tool_use/tool_result integrity (it only cuts at a
96
+ // completed turn boundary), so adopting its result mid-turn is safe.
97
+ if (args.compact) {
98
+ messages = await args.compact(messages);
99
+ }
91
100
  iterations = i + 1;
92
101
  const tools = registry.toToolSpecs();
93
102
  // ── Consume one model turn ──────────────────────────────────────────────
@@ -145,23 +145,46 @@ export declare class Session {
145
145
  /** Drop the conversation history but keep the session (for `/clear`). */
146
146
  clear(): void;
147
147
  /**
148
- * Compact only when the estimated history exceeds
149
- * `compactThreshold * maxTokens`. On success logs a one-line notice and
150
- * returns the number of older messages folded into the summary; otherwise
151
- * returns `null` (under threshold, nothing safe to cut, or summary failed).
148
+ * Compact `this.messages` only when it has grown past threshold, adopting the
149
+ * result. On success logs a one-line notice and returns the number of older
150
+ * messages folded into the summary; otherwise returns `null` (under threshold,
151
+ * nothing safe to cut, or summary failed).
152
152
  */
153
153
  maybeCompact(onRequestUsage?: (req: RequestUsage) => void): Promise<number | null>;
154
+ /**
155
+ * The mid-loop compaction seam (build item 3) handed to {@link runAgent}: same
156
+ * threshold/cut/summarize path as {@link maybeCompact}, but over the loop's own
157
+ * running history rather than `this.messages` (the loop owns and adopts its
158
+ * copy). Reuses the exact machinery so no summarization logic is duplicated and
159
+ * the loop stays ignorant of it. Under threshold it returns the history
160
+ * unchanged — cheap, no model call.
161
+ */
162
+ private compactLoopHistory;
154
163
  /**
155
164
  * Force compaction regardless of the threshold (backs `/compact`). Returns the
156
165
  * number of older messages summarized, or `null` if there was nothing safe to
157
166
  * cut or the summary call failed.
158
167
  */
159
168
  compact(): Promise<number | null>;
169
+ /**
170
+ * Compact `messages` when its estimated footprint exceeds
171
+ * `compactThreshold * maxTokens`, else return it untouched. The estimate adds a
172
+ * fixed `reserveTokens` allowance for the system prompt and tool schemas that
173
+ * {@link estimateTokens} never sees (~4.5k+ tokens of real request payload), so
174
+ * the trigger reflects the actual request size rather than only the visible
175
+ * history — otherwise the loop can sit just under the visible threshold while
176
+ * the real request has already overrun the window. Logs a one-line notice on a
177
+ * successful compaction.
178
+ */
179
+ private compactIfOverThreshold;
160
180
  /**
161
181
  * Find a clean cut, summarize the older prefix into a synthetic user/assistant
162
182
  * pair, and splice it in front of the kept-recent messages. Best-effort: a
163
- * failed summary call leaves the history untouched and returns `null` (fail
164
- * open — losing compaction is degraded, not unsafe).
183
+ * failed summary call leaves the history untouched and reports `compacted:
184
+ * null` (fail open — losing compaction is degraded, not unsafe). Pure with
185
+ * respect to `this.messages`: it returns the new array for the caller to adopt
186
+ * (the loop and the session each own their own history), and only accumulates
187
+ * the summary's usage into the session total.
165
188
  */
166
189
  private runCompaction;
167
190
  /**
@@ -171,7 +194,9 @@ export declare class Session {
171
194
  * matching `tool_result` (the next user message) must never straddle the cut,
172
195
  * or the next provider call breaks. A real user *prompt* (`role:"user"` with
173
196
  * string content) only occurs at a completed turn boundary, where every prior
174
- * tool exchange is already resolved — so the kept region must begin there.
197
+ * tool exchange is already resolved — so the kept region must begin there. The
198
+ * synthetic compaction-summary user message is also string content, so a
199
+ * repeat compaction always finds at least the previous summary as a clean cut.
175
200
  *
176
201
  * Start from `length - keepRecentMessages` and walk *backwards* to the nearest
177
202
  * such prompt: this keeps at least the recent floor and lands clean. Returns
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { loadProjectInstructions } from "../config/index.js";
3
3
  import { resolveTaskModel } from "../routing/index.js";
4
4
  import { UsageCollector, } from "../usage/index.js";
5
+ import { Budget } from "./budget.js";
5
6
  import { runAgent, } from "./loop.js";
6
7
  import { SUMMARY_SYSTEM, COMPACTION_MARKER } from "./prompts.js";
7
8
  /**
@@ -115,6 +116,20 @@ export class Session {
115
116
  const onReq = (req) => collector.record(req);
116
117
  // Compact *before* the agent call so the turn runs against a bounded history.
117
118
  await this.maybeCompact(onReq);
119
+ // Per-turn runaway guard (build item 4): when `agent.maxTokensPerTurn` is
120
+ // set, hand the loop a fresh token-only budget for THIS turn. Reusing the
121
+ // Budget primitive with an infinite iteration cap makes it purely a token
122
+ // stop — the loop's own `agent.maxIterations` already bounds turn count.
123
+ // Unset/0 → no budget object at all, so the loop's budget check is a no-op
124
+ // and behavior is byte-identical to before. Rebuilt each `send`, so the cap
125
+ // is per-turn, never cumulative across the session (cost is C.22's concern).
126
+ const maxTokensPerTurn = this.args.config.agent.maxTokensPerTurn;
127
+ const budget = maxTokensPerTurn > 0
128
+ ? new Budget({
129
+ maxIterations: Number.POSITIVE_INFINITY,
130
+ maxTokens: maxTokensPerTurn,
131
+ })
132
+ : undefined;
118
133
  // before-run (C.19): a blocking pre-run hook — or an untrusted project's
119
134
  // hooks — throws here and aborts the turn before the model is engaged
120
135
  // (fail-closed). No-op when hooks are disabled or none are registered.
@@ -133,12 +148,21 @@ export class Session {
133
148
  : await runAgent({
134
149
  messages: this.messages,
135
150
  ...this.args, // carries `router` through to the loop
151
+ // The per-turn token guard (build item 4). After the spread because
152
+ // SessionArgs has no `budget` field — it is a per-turn construction,
153
+ // not session state. `undefined` when the cap is off (no-op check).
154
+ budget,
136
155
  taskClass: "main-turn",
137
156
  // After the spread so a mid-session `/reload` wins over the initial value.
138
157
  projectInstructions: this.projectInstructions,
139
158
  planMode: false, // the plan directive belongs only to the runner's propose phase
140
159
  renderer,
141
160
  onRequestUsage: onReq,
161
+ // Mid-loop compaction (build item 3): let a long autonomous turn
162
+ // compact between iterations, not just once up front. Reuses this
163
+ // session's threshold/cut/summarize path over the loop's own history
164
+ // and attributes the summary usage to this run's collector.
165
+ compact: (messages) => this.compactLoopHistory(messages, onReq),
142
166
  });
143
167
  this.messages = result.messages;
144
168
  this.usage.input_tokens += result.usage.input_tokens;
@@ -169,21 +193,27 @@ export class Session {
169
193
  this.messages = [];
170
194
  }
171
195
  /**
172
- * Compact only when the estimated history exceeds
173
- * `compactThreshold * maxTokens`. On success logs a one-line notice and
174
- * returns the number of older messages folded into the summary; otherwise
175
- * returns `null` (under threshold, nothing safe to cut, or summary failed).
196
+ * Compact `this.messages` only when it has grown past threshold, adopting the
197
+ * result. On success logs a one-line notice and returns the number of older
198
+ * messages folded into the summary; otherwise returns `null` (under threshold,
199
+ * nothing safe to cut, or summary failed).
176
200
  */
177
201
  async maybeCompact(onRequestUsage) {
178
- const { maxTokens, compactThreshold } = this.args.config.context;
179
- if (estimateTokens(this.messages) <= compactThreshold * maxTokens) {
180
- return null;
181
- }
182
- const n = await this.runCompaction(onRequestUsage);
183
- if (n) {
184
- this.args.ctx.logger.info(`compacted ${n} older message${n === 1 ? "" : "s"} to stay within context`);
185
- }
186
- return n;
202
+ const { messages, compacted } = await this.compactIfOverThreshold(this.messages, onRequestUsage);
203
+ this.messages = messages;
204
+ return compacted;
205
+ }
206
+ /**
207
+ * The mid-loop compaction seam (build item 3) handed to {@link runAgent}: same
208
+ * threshold/cut/summarize path as {@link maybeCompact}, but over the loop's own
209
+ * running history rather than `this.messages` (the loop owns and adopts its
210
+ * copy). Reuses the exact machinery so no summarization logic is duplicated and
211
+ * the loop stays ignorant of it. Under threshold it returns the history
212
+ * unchanged — cheap, no model call.
213
+ */
214
+ async compactLoopHistory(messages, onRequestUsage) {
215
+ const result = await this.compactIfOverThreshold(messages, onRequestUsage);
216
+ return result.messages;
187
217
  }
188
218
  /**
189
219
  * Force compaction regardless of the threshold (backs `/compact`). Returns the
@@ -191,20 +221,47 @@ export class Session {
191
221
  * cut or the summary call failed.
192
222
  */
193
223
  async compact() {
194
- return this.runCompaction();
224
+ const { messages, compacted } = await this.runCompaction(this.messages);
225
+ this.messages = messages;
226
+ return compacted;
227
+ }
228
+ /**
229
+ * Compact `messages` when its estimated footprint exceeds
230
+ * `compactThreshold * maxTokens`, else return it untouched. The estimate adds a
231
+ * fixed `reserveTokens` allowance for the system prompt and tool schemas that
232
+ * {@link estimateTokens} never sees (~4.5k+ tokens of real request payload), so
233
+ * the trigger reflects the actual request size rather than only the visible
234
+ * history — otherwise the loop can sit just under the visible threshold while
235
+ * the real request has already overrun the window. Logs a one-line notice on a
236
+ * successful compaction.
237
+ */
238
+ async compactIfOverThreshold(messages, onRequestUsage) {
239
+ const { maxTokens, compactThreshold, reserveTokens } = this.args.config.context;
240
+ const estimated = estimateTokens(messages) + reserveTokens;
241
+ if (estimated <= compactThreshold * maxTokens) {
242
+ return { messages, compacted: null };
243
+ }
244
+ const result = await this.runCompaction(messages, onRequestUsage);
245
+ if (result.compacted) {
246
+ this.args.ctx.logger.info(`compacted ${result.compacted} older message${result.compacted === 1 ? "" : "s"} to stay within context`);
247
+ }
248
+ return result;
195
249
  }
196
250
  /**
197
251
  * Find a clean cut, summarize the older prefix into a synthetic user/assistant
198
252
  * pair, and splice it in front of the kept-recent messages. Best-effort: a
199
- * failed summary call leaves the history untouched and returns `null` (fail
200
- * open — losing compaction is degraded, not unsafe).
253
+ * failed summary call leaves the history untouched and reports `compacted:
254
+ * null` (fail open — losing compaction is degraded, not unsafe). Pure with
255
+ * respect to `this.messages`: it returns the new array for the caller to adopt
256
+ * (the loop and the session each own their own history), and only accumulates
257
+ * the summary's usage into the session total.
201
258
  */
202
- async runCompaction(onRequestUsage) {
203
- const cut = this.findCut();
259
+ async runCompaction(messages, onRequestUsage) {
260
+ const cut = this.findCut(messages);
204
261
  if (cut === null)
205
- return null;
206
- const prefix = this.messages.slice(0, cut);
207
- const kept = this.messages.slice(cut);
262
+ return { messages, compacted: null };
263
+ const prefix = messages.slice(0, cut);
264
+ const kept = messages.slice(cut);
208
265
  let synopsis;
209
266
  try {
210
267
  const summary = await this.summarize(prefix, onRequestUsage);
@@ -214,7 +271,7 @@ export class Session {
214
271
  }
215
272
  catch (err) {
216
273
  this.args.ctx.logger.warn(`compaction skipped: summary failed (${err.message})`);
217
- return null;
274
+ return { messages, compacted: null };
218
275
  }
219
276
  // A user/assistant pair, not a lone message: the kept region begins with a
220
277
  // user prompt, so a single synthetic user message would put two user turns
@@ -229,8 +286,10 @@ export class Session {
229
286
  content: `${COMPACTION_MARKER} Summary of the conversation so far:\n\n${synopsis}`,
230
287
  },
231
288
  ];
232
- this.messages = [...summaryMessages, ...kept];
233
- return prefix.length;
289
+ return {
290
+ messages: [...summaryMessages, ...kept],
291
+ compacted: prefix.length,
292
+ };
234
293
  }
235
294
  /**
236
295
  * Choose the boundary between the summarized prefix and the kept-recent tail.
@@ -239,18 +298,20 @@ export class Session {
239
298
  * matching `tool_result` (the next user message) must never straddle the cut,
240
299
  * or the next provider call breaks. A real user *prompt* (`role:"user"` with
241
300
  * string content) only occurs at a completed turn boundary, where every prior
242
- * tool exchange is already resolved — so the kept region must begin there.
301
+ * tool exchange is already resolved — so the kept region must begin there. The
302
+ * synthetic compaction-summary user message is also string content, so a
303
+ * repeat compaction always finds at least the previous summary as a clean cut.
243
304
  *
244
305
  * Start from `length - keepRecentMessages` and walk *backwards* to the nearest
245
306
  * such prompt: this keeps at least the recent floor and lands clean. Returns
246
307
  * the cut index, or `null` if no safe boundary leaves a non-empty prefix
247
308
  * (e.g. a single long in-progress turn — nothing safe to compact).
248
309
  */
249
- findCut() {
310
+ findCut(messages) {
250
311
  const { keepRecentMessages } = this.args.config.context;
251
- const start = this.messages.length - keepRecentMessages;
312
+ const start = messages.length - keepRecentMessages;
252
313
  for (let i = start; i >= 1; i--) {
253
- const msg = this.messages[i];
314
+ const msg = messages[i];
254
315
  if (msg.role === "user" && typeof msg.content === "string")
255
316
  return i;
256
317
  }
@@ -131,7 +131,7 @@ export function mcpCommand() {
131
131
  ]);
132
132
  }
133
133
  const io = defaultOnboardingIO(shouldUseColor(process.stderr));
134
- io.write(`${t.strong(`credential for "${server}"`)} ${t.muted(`(stored as "${ref}" in ~/.cruxy/credentials.json, 0600)`)}\n`);
134
+ io.write(`${t.strong(`credential for "${server}"`)} ${t.muted(`(stored as "${ref}" in ~/.cruxy/credentials.json, owner-only)`)}\n`);
135
135
  io.write(`${t.muted("paste the bearer token (input hidden): ")}`);
136
136
  const token = (await io.readSecret()).trim();
137
137
  if (!token) {
@@ -9,11 +9,10 @@ export declare function readCredential(provider: string, file?: string): string
9
9
  * secret is sourced from. Never throws.
10
10
  */
11
11
  export declare function readMcpCredential(ref: string, file?: string): string | undefined;
12
- /** Persist MCP bearer token for credential name `ref`. Same 0600/0700 as keys. */
12
+ /** Persist MCP bearer token for credential name `ref`. Same owner-only guarantee. */
13
13
  export declare function writeMcpCredential(ref: string, token: string, file?: string): void;
14
14
  /**
15
- * Persist `key` for `provider`, merging into any existing store. The file is
16
- * written `0600` and its directory `0700` so the secret is owner-only — enforced
17
- * with an explicit `chmod` after write (mkdir/write modes are umask-masked).
15
+ * Persist `key` for `provider`, merging into any existing store. Written
16
+ * owner-only (see {@link writeInto}); refuses loudly if that can't be enforced.
18
17
  */
19
18
  export declare function writeCredential(provider: string, key: string, file?: string): void;
@@ -1,13 +1,23 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { CREDENTIALS_FILE_NAME } from "../constants.js";
4
+ import { credentialsUnprotected } from "../errors/index.js";
5
+ import { logger } from "../utils/logger.js";
6
+ import { enforceOwnerOnly, isOwnerOnly } from "./owner-only.js";
4
7
  import { globalDir } from "./paths.js";
5
8
  /**
6
9
  * The credentials store (U.6) — the one place a provider API key is persisted.
7
10
  * It lives **outside** `config.json` on purpose: config is secret-free by design
8
11
  * ("the API key comes from env"), so secrets get their own file with restrictive
9
- * permissions (`0600`, dir `0700`), the same shape as gh/aws/npm. `resolveApiKey`
10
- * reads it as a fallback after the environment.
12
+ * permissions, the same shape as gh/aws/npm. `resolveApiKey` reads it as a
13
+ * fallback after the environment.
14
+ *
15
+ * "Restrictive" means **owner-only**: POSIX `0600` (dir `0700`), and on Windows
16
+ * an NTFS ACL granting only the current user (POSIX modes are meaningless there —
17
+ * see {@link enforceOwnerOnly}). The guarantee is enforced AND verified on every
18
+ * write; if it cannot be established the write is refused loudly
19
+ * (`CRUXY_E_CREDENTIALS_UNPROTECTED`) rather than persisting a secret at
20
+ * permissions we could not secure.
11
21
  */
12
22
  /** Bumped if the on-disk shape ever changes. */
13
23
  const CREDENTIALS_VERSION = 1;
@@ -15,6 +25,26 @@ const CREDENTIALS_VERSION = 1;
15
25
  export function credentialsPath() {
16
26
  return join(globalDir(), CREDENTIALS_FILE_NAME);
17
27
  }
28
+ /** Paths already warned about this process, so a loose-perms warning fires once. */
29
+ const warnedLoosePerms = new Set();
30
+ /**
31
+ * Best-effort: warn (never refuse) if an existing store is readable beyond its
32
+ * owner, so an upgrade from a build that couldn't secure it isn't silently
33
+ * insecure — and isn't bricked either. Fires at most once per path per process.
34
+ */
35
+ function warnIfLoosePerms(file) {
36
+ if (warnedLoosePerms.has(file))
37
+ return;
38
+ warnedLoosePerms.add(file);
39
+ try {
40
+ if (existsSync(file) && !isOwnerOnly(file)) {
41
+ logger.warn(`credentials store ${file} is not owner-only — other users on this machine may be able to read it. Re-run \`cruxy login\` (or re-store the MCP credential) to repair its permissions.`);
42
+ }
43
+ }
44
+ catch {
45
+ // Perms could not be inspected — stay silent rather than cry wolf.
46
+ }
47
+ }
18
48
  /** Parse the store at `file`, or `null` if absent/unreadable/malformed. */
19
49
  function readStore(file) {
20
50
  if (!existsSync(file))
@@ -35,6 +65,7 @@ function readStore(file) {
35
65
  }
36
66
  /** The stored key for `provider`, or `undefined`. Never throws. */
37
67
  export function readCredential(provider, file = credentialsPath()) {
68
+ warnIfLoosePerms(file);
38
69
  const store = readStore(file);
39
70
  const key = store?.keys[provider];
40
71
  return typeof key === "string" && key !== "" ? key : undefined;
@@ -46,52 +77,74 @@ export function readCredential(provider, file = credentialsPath()) {
46
77
  * secret is sourced from. Never throws.
47
78
  */
48
79
  export function readMcpCredential(ref, file = credentialsPath()) {
80
+ warnIfLoosePerms(file);
49
81
  const store = readStore(file);
50
82
  const token = store?.mcp?.[ref];
51
83
  return typeof token === "string" && token !== "" ? token : undefined;
52
84
  }
53
- /** Persist MCP bearer token for credential name `ref`. Same 0600/0700 as keys. */
85
+ /** Persist MCP bearer token for credential name `ref`. Same owner-only guarantee. */
54
86
  export function writeMcpCredential(ref, token, file = credentialsPath()) {
55
87
  writeInto(file, (store) => {
56
88
  store.mcp ??= {};
57
89
  store.mcp[ref] = token;
58
- });
90
+ }, "mcp");
59
91
  }
60
92
  /**
61
- * Persist `key` for `provider`, merging into any existing store. The file is
62
- * written `0600` and its directory `0700` so the secret is owner-only — enforced
63
- * with an explicit `chmod` after write (mkdir/write modes are umask-masked).
93
+ * Persist `key` for `provider`, merging into any existing store. Written
94
+ * owner-only (see {@link writeInto}); refuses loudly if that can't be enforced.
64
95
  */
65
96
  export function writeCredential(provider, key, file = credentialsPath()) {
66
97
  writeInto(file, (store) => {
67
98
  store.keys[provider] = key;
68
- });
99
+ }, "provider");
69
100
  }
70
101
  /**
71
- * Merge `mutate` into the store and persist it owner-only: dir `0700`, file
72
- * `0600`, enforced with an explicit `chmod` after write (mkdir/write modes are
73
- * umask-masked). The one write path shared by every credential namespace.
102
+ * Merge `mutate` into the store and persist it owner-only. The one write path
103
+ * shared by every credential namespace, and the single place the owner-only
104
+ * guarantee is enforced:
105
+ *
106
+ * 1. The DIRECTORY is made owner-only FIRST, before any secret is written — so
107
+ * the file inherits owner-only at creation (no window where it exists under
108
+ * inherited permissions), and if the directory can't be secured we refuse
109
+ * before a secret ever touches disk.
110
+ * 2. The new content is written to a temp file, made owner-only + VERIFIED,
111
+ * then atomically renamed over the target. A failure removes the temp and
112
+ * leaves any existing store untouched — never a torn or clobbered write.
113
+ *
114
+ * Enforcement runs on every write, so a pre-existing store with loose
115
+ * permissions is repaired in place. If owner-only cannot be established the write
116
+ * is refused with `CRUXY_E_CREDENTIALS_UNPROTECTED` (`kind` tailors the
117
+ * remediation: provider keys → env var; MCP tokens → no env fallback).
74
118
  */
75
- function writeInto(file, mutate) {
119
+ function writeInto(file, mutate, kind) {
76
120
  const dir = dirname(file);
77
- mkdirSync(dir, { recursive: true, mode: 0o700 });
121
+ mkdirSync(dir, { recursive: true });
78
122
  try {
79
- chmodSync(dir, 0o700);
123
+ enforceOwnerOnly(dir, { directory: true });
80
124
  }
81
- catch {
82
- // Best-effort on platforms without POSIX modes (e.g. Windows).
125
+ catch (err) {
126
+ // Refuse BEFORE writing any secret nothing sensitive has hit disk yet.
127
+ throw credentialsUnprotected(kind, dir, err);
83
128
  }
84
129
  const store = readStore(file) ?? { version: CREDENTIALS_VERSION, keys: {} };
85
130
  store.version = CREDENTIALS_VERSION;
86
131
  mutate(store);
87
- writeFileSync(file, JSON.stringify(store, null, 2) + "\n", {
132
+ const tmp = `${file}.tmp-${process.pid}`;
133
+ writeFileSync(tmp, JSON.stringify(store, null, 2) + "\n", {
88
134
  encoding: "utf8",
89
135
  mode: 0o600,
90
136
  });
91
137
  try {
92
- chmodSync(file, 0o600);
138
+ enforceOwnerOnly(tmp, { directory: false }); // sets + verifies, or throws
139
+ renameSync(tmp, file); // atomic replace; the owner-only ACL moves with it
93
140
  }
94
- catch {
95
- // Best-effort (see above).
141
+ catch (err) {
142
+ try {
143
+ rmSync(tmp, { force: true });
144
+ }
145
+ catch {
146
+ // The temp may already be gone; the target store is untouched regardless.
147
+ }
148
+ throw credentialsUnprotected(kind, file, err);
96
149
  }
97
150
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Make `path` owner-only, or throw. On Windows the ACL is verified after the
3
+ * edit (both the `icacls` exit code AND a read-back), so a returned call is a
4
+ * genuine guarantee, never a best-effort attempt.
5
+ *
6
+ * @throws if owner-only permissions cannot be established (non-zero `icacls`,
7
+ * an unresolvable SID, a filesystem without ACLs/modes, …).
8
+ */
9
+ export declare function enforceOwnerOnly(path: string, opts?: {
10
+ directory?: boolean;
11
+ }): void;
12
+ /**
13
+ * Whether `path` is currently owner-only. POSIX: no group/other bits. Windows:
14
+ * best-effort — the ACL names no broad principal (Everyone / Authenticated
15
+ * Users / Users). Used both to verify {@link enforceOwnerOnly} and to warn on a
16
+ * pre-existing store with loose permissions. Returns `true` when it genuinely
17
+ * cannot tell (a missing tool), so a warning path never cries wolf.
18
+ */
19
+ export declare function isOwnerOnly(path: string): boolean;