docks-kit 0.21.0 → 0.21.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.
@@ -1,15 +1,17 @@
1
1
  /**
2
2
  * Run overlay for `docks-kit omp`. The overlay merges over the deployed omp
3
3
  * config for one run only. It sets the 16 roles in ROLE_ORDER to the free
4
- * model and empties the 13 retry chains in FALLBACK_ORDER. omp merges the
5
- * overlay key by key, so each deployed retry chain that is not in
6
- * FALLBACK_ORDER stays as deployed. The `web` role and its retry chain are
7
- * not in the overlay, so the deployed web-search provider order applies, and
8
- * that order can include a paid chat model. A deployed `plan`, `slow`, or
9
- * `designer` chain also stays and can name a paid model. Every other key
10
- * falls through to the deployed config.
4
+ * model and empties the 13 retry chains in FALLBACK_ORDER and the chains keyed
5
+ * by the free model. omp merges the overlay key by key, so each deployed retry
6
+ * chain that is not in FALLBACK_ORDER stays as deployed. The `web` role and
7
+ * its retry chain are not in the overlay, so the deployed web-search provider
8
+ * order applies, and that order can include a paid chat model. A deployed
9
+ * `plan`, `slow`, or `designer` chain also stays, but a retry of the free
10
+ * model uses the empty chain keyed by that model first. Every other key falls
11
+ * through to the deployed config.
11
12
  */
12
13
  import { createHash } from "node:crypto";
14
+ import { delimiter } from "node:path";
13
15
  import type { OmpSessionModel } from "./harnesses";
14
16
 
15
17
  export interface CatalogModel {
@@ -199,42 +201,110 @@ export function advisorRecommendation(
199
201
  return known[Math.max(0, index - 2)];
200
202
  }
201
203
 
204
+ /** A thinking level the overlay can render, or undefined for a blank one. */
205
+ function renderableLevel(level: string | undefined): string | undefined {
206
+ return typeof level === "string" && level.trim() !== "" ? level : undefined;
207
+ }
208
+
209
+ /**
210
+ * The value the overlay gives one role. The overlay, the session `--model`,
211
+ * and the child environment all use it, so the three cannot drift apart. A
212
+ * model without a level gets the bare selector so the deployed level applies.
213
+ */
214
+ function roleValue(model: OmpSessionModel, role: string): string {
215
+ const thinking = renderableLevel(model.thinking);
216
+ if (thinking === undefined) return model.selector;
217
+ const level =
218
+ role === "advisor" ? (renderableLevel(model.advisorThinking) ?? thinking) : thinking;
219
+ return `${model.selector}:${level}`;
220
+ }
221
+
202
222
  /**
203
223
  * Render the run overlay as YAML text. Empty fallback chains keep a retry
204
224
  * from falling back onto a paid model. A model without a level renders bare
205
225
  * selectors with no thinking keys so the deployed values apply.
206
226
  */
207
227
  export function renderFreeOverlay(model: OmpSessionModel): string {
208
- const thinking =
209
- typeof model.thinking === "string" && model.thinking.trim() !== "" ? model.thinking : undefined;
228
+ const thinking = renderableLevel(model.thinking);
210
229
  const lines: Array<string> = ["# Generated per run by docks-kit omp. Edits are overwritten."];
211
- if (thinking !== undefined) {
212
- lines.push(`defaultThinkingLevel: ${thinking}`, "modelRoles:");
213
- const advisor =
214
- typeof model.advisorThinking === "string" && model.advisorThinking.trim() !== ""
215
- ? model.advisorThinking
216
- : thinking;
217
- for (const role of ROLE_ORDER) {
218
- lines.push(` ${role}: ${model.selector}:${role === "advisor" ? advisor : thinking}`);
219
- }
220
- lines.push("task:", ` maxEffort: ${thinking}`);
221
- } else {
222
- lines.push("modelRoles:");
223
- for (const role of ROLE_ORDER) {
224
- lines.push(` ${role}: ${model.selector}`);
225
- }
230
+ if (thinking !== undefined) lines.push(`defaultThinkingLevel: ${thinking}`);
231
+ lines.push("modelRoles:");
232
+ for (const role of ROLE_ORDER) {
233
+ lines.push(` ${role}: ${roleValue(model, role)}`);
226
234
  }
235
+ if (thinking !== undefined) lines.push("task:", ` maxEffort: ${thinking}`);
227
236
  lines.push("retry:", " fallbackChains:");
228
237
  for (const chain of FALLBACK_ORDER) {
229
238
  lines.push(` ${chain}: []`);
230
239
  }
240
+ // A chain keyed by the selector outranks a role chain, so a project or
241
+ // PI_CONFIG_FILES chain for the free model could otherwise reach a paid
242
+ // model. The session can run the model at any level, `off` included.
243
+ for (const level of [undefined, "off", ...THINKING_LADDER]) {
244
+ const key = level === undefined ? model.selector : `${model.selector}:${level}`;
245
+ lines.push(` ${JSON.stringify(key)}: []`);
246
+ }
231
247
  return `${lines.join("\n")}\n`;
232
248
  }
233
249
 
234
- /** Build the omp argv with the overlay flag ahead of the forwarded args. */
250
+ /**
251
+ * Build the omp argv. `launch` first makes omp read every forwarded word as
252
+ * message text, so no omp subcommand, with its own model selection, runs
253
+ * through the launcher. The explicit `--model` outranks a restored session
254
+ * model, so `--continue` and `--resume` keep the free model.
255
+ */
235
256
  export function buildOmpArgs(
236
257
  overlayPath: string,
258
+ session: OmpSessionModel,
237
259
  passthrough: ReadonlyArray<string>,
238
260
  ): ReadonlyArray<string> {
239
- return ["--config", overlayPath, ...passthrough];
261
+ return [
262
+ "launch",
263
+ "--config",
264
+ overlayPath,
265
+ "--model",
266
+ roleValue(session, "default"),
267
+ ...passthrough,
268
+ ];
269
+ }
270
+
271
+ // Variables that omp reads at launch to set a role above every config layer.
272
+ const MODEL_ENV_ROLES: ReadonlyArray<readonly [string, string]> = [
273
+ ["PI_SMOL_MODEL", "smol"],
274
+ ["PI_SLOW_MODEL", "slow"],
275
+ ["PI_PLAN_MODEL", "plan"],
276
+ ];
277
+
278
+ export interface OmpChildEnvironment {
279
+ readonly env: Record<string, string | undefined>;
280
+ /** Model variables whose non-empty parent value the overlay value replaced. */
281
+ readonly replaced: ReadonlyArray<string>;
282
+ }
283
+
284
+ /**
285
+ * The omp session environment. The model variables get the overlay role
286
+ * values, because removing them would let a `.env` file refill them. The
287
+ * overlay joins PI_CONFIG_FILES, so an omp that the session's bash tool
288
+ * starts loads it too.
289
+ */
290
+ export function ompChildEnvironment(
291
+ parent: Readonly<Record<string, string | undefined>>,
292
+ overlayPath: string,
293
+ session: OmpSessionModel,
294
+ ): OmpChildEnvironment {
295
+ const inherited = (parent["PI_CONFIG_FILES"] ?? "")
296
+ .split(delimiter)
297
+ .filter((entry) => entry !== "");
298
+ const env: Record<string, string | undefined> = {
299
+ ...parent,
300
+ PI_CONFIG_FILES: [...inherited, overlayPath].join(delimiter),
301
+ };
302
+ const replaced: Array<string> = [];
303
+ for (const [name, role] of MODEL_ENV_ROLES) {
304
+ const value = roleValue(session, role);
305
+ const previous = parent[name];
306
+ if (previous !== undefined && previous !== "" && previous !== value) replaced.push(name);
307
+ env[name] = value;
308
+ }
309
+ return { env, replaced };
240
310
  }
@@ -8,6 +8,9 @@
8
8
  * the holder checks staleness again before it removes the lock. Thus two
9
9
  * runs never both remove a stale lock and both create a new one.
10
10
  * - A run removes the lock and the mutex only while they still hold its token.
11
+ * - On Windows, another process can delete or hold the lock or the mutex while
12
+ * a run reads or removes it. Such a path counts as absent, and only the
13
+ * exclusive create decides the result.
11
14
  */
12
15
  import { randomBytes } from "node:crypto";
13
16
  import {
@@ -35,13 +38,31 @@ function errorCode(cause: unknown): string | undefined {
35
38
  : undefined;
36
39
  }
37
40
 
38
- /** Create `path` with `wx` and write `text`; false when the path exists. */
41
+ /**
42
+ * Windows keeps a deleted file "delete pending" while a handle to it is open,
43
+ * and refuses a new open of that name with ERROR_ACCESS_DENIED. A delete of a
44
+ * file that another process holds without delete sharing fails with
45
+ * ERROR_SHARING_VIOLATION. libuv, which runs the `node:fs` calls of Bun and
46
+ * Node.js on Windows, reports these errors as EPERM and EBUSY.
47
+ */
48
+ const WINDOWS_CONTENTION: Record<string, true> = { EBUSY: true, EPERM: true };
49
+
50
+ /** True on Windows for an error that another process causes when it deletes or holds the path. */
51
+ function isWindowsContention(cause: unknown): boolean {
52
+ const code = errorCode(cause);
53
+ return process.platform === "win32" && code !== undefined && WINDOWS_CONTENTION[code] === true;
54
+ }
55
+
56
+ /**
57
+ * Create `path` with `wx` and write `text`. False when the path exists or, on
58
+ * Windows, when another process deletes it now.
59
+ */
39
60
  function createExclusive(path: string, text: string): boolean {
40
61
  let fd: number;
41
62
  try {
42
63
  fd = openSync(path, "wx", 0o600);
43
64
  } catch (cause) {
44
- if (errorCode(cause) === "EEXIST") return false;
65
+ if (errorCode(cause) === "EEXIST" || isWindowsContention(cause)) return false;
45
66
  throw cause;
46
67
  }
47
68
  try {
@@ -52,13 +73,13 @@ function createExclusive(path: string, text: string): boolean {
52
73
  return true;
53
74
  }
54
75
 
55
- /** `lstat`, `undefined` when absent; any other error throws. */
76
+ /** `lstat`; `undefined` when absent or, on Windows, when another process deletes it. */
56
77
  function lstatIfPresent(path: string): Stats | undefined {
57
78
  try {
58
79
  return lstatSync(path);
59
80
  } catch (cause) {
60
81
  const code = errorCode(cause);
61
- if (code === "ENOENT" || code === "ENOTDIR") return undefined;
82
+ if (code === "ENOENT" || code === "ENOTDIR" || isWindowsContention(cause)) return undefined;
62
83
  throw cause;
63
84
  }
64
85
  }
@@ -71,11 +92,15 @@ function readText(path: string): string | undefined {
71
92
  }
72
93
  }
73
94
 
95
+ /**
96
+ * Remove `path`. Ignore a path that is absent or, on Windows, a path that
97
+ * another process deletes or holds.
98
+ */
74
99
  function unlinkIfPresent(path: string): void {
75
100
  try {
76
101
  unlinkSync(path);
77
102
  } catch (cause) {
78
- if (errorCode(cause) !== "ENOENT") throw cause;
103
+ if (errorCode(cause) !== "ENOENT" && !isWindowsContention(cause)) throw cause;
79
104
  }
80
105
  }
81
106