pi-opencode-go-provider 1.1.61 → 1.1.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/config.ts CHANGED
@@ -10,6 +10,7 @@ import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
12
12
  import { GLYPH_MODES, type GlyphMode } from "./glyphs.ts";
13
+ import { updateSettingsFile } from "./settings-file.ts";
13
14
 
14
15
  export const PROVIDER_ID = "opencode-go";
15
16
  export const CONFIG_BASENAME = "opencode-go-provider.json";
@@ -123,19 +124,13 @@ export function readUsageConfig(env: NodeJS.ProcessEnv = process.env): UsageConf
123
124
  /** Merge a patch into the config file, preserving unrelated keys. */
124
125
  export function writeUsageConfig(patch: Partial<UsageConfig>): boolean {
125
126
  try {
126
- const file = configPath();
127
- let document: Record<string, unknown> = {};
128
- try {
129
- const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
130
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
131
- document = parsed as Record<string, unknown>;
127
+ updateSettingsFile(configPath(), (document) => {
128
+ const usage = document.usage;
129
+ if (usage !== undefined && (!usage || typeof usage !== "object" || Array.isArray(usage))) {
130
+ throw new Error("Expected a usage settings object");
132
131
  }
133
- } catch {
134
- document = {};
135
- }
136
- document.usage = { ...readFileUsage(), ...patch };
137
- fs.mkdirSync(path.dirname(file), { recursive: true });
138
- fs.writeFileSync(file, `${JSON.stringify(document, null, 2)}\n`);
132
+ return { ...document, usage: { ...usage, ...patch } };
133
+ });
139
134
  return true;
140
135
  } catch {
141
136
  return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-opencode-go-provider",
3
- "version": "1.1.61",
3
+ "version": "1.1.62",
4
4
  "description": "Opencode Go provider extension for pi - Fast, efficient GLM, Kimi, and MiniMax models through the opencode.ai API",
5
5
  "type": "module",
6
6
  "main": "index.ts",
@@ -0,0 +1,80 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { performance } from "node:perf_hooks";
5
+
6
+ const errorCode = (error: unknown) => (error as NodeJS.ErrnoException)?.code;
7
+
8
+ function resolveTarget(file: string): string {
9
+ fs.mkdirSync(path.dirname(file), { recursive: true });
10
+ try {
11
+ return fs.realpathSync(file);
12
+ } catch (error) {
13
+ if (errorCode(error) !== "ENOENT") throw error;
14
+ // Do not replace a dangling symlink with a regular file.
15
+ if (fs.lstatSync(file, { throwIfNoEntry: false })) throw error;
16
+ return path.join(fs.realpathSync(path.dirname(file)), path.basename(file));
17
+ }
18
+ }
19
+
20
+ function readSettings(file: string): { document: Record<string, unknown>; mode?: number } {
21
+ const stat = fs.statSync(file, { throwIfNoEntry: false });
22
+ if (!stat) return { document: {} };
23
+ if (!stat.isFile()) throw new Error(`Not a settings file: ${file}`);
24
+ const document: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
25
+ if (!document || typeof document !== "object" || Array.isArray(document)) {
26
+ throw new Error(`Expected a settings object in ${file}`);
27
+ }
28
+ return { document: document as Record<string, unknown>, mode: stat.mode & 0o777 };
29
+ }
30
+
31
+ function publish(file: string, document: Record<string, unknown>, mode?: number): void {
32
+ const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${randomUUID()}.tmp`);
33
+ const fd = fs.openSync(temporary, "wx", mode ?? 0o600);
34
+ try {
35
+ try {
36
+ fs.writeFileSync(fd, JSON.stringify(document, null, 2) + "\n", "utf8");
37
+ if (mode !== undefined) fs.fchmodSync(fd, mode);
38
+ } finally {
39
+ fs.closeSync(fd);
40
+ }
41
+ fs.renameSync(temporary, file);
42
+ } catch (error) {
43
+ try { fs.unlinkSync(temporary); } catch { /* preserve the original error */ }
44
+ throw error;
45
+ }
46
+ }
47
+
48
+ /** Serialize cooperating writers around read, update and atomic publication. */
49
+ export function updateSettingsFile(
50
+ file: string,
51
+ update: (document: Record<string, unknown>) => Record<string, unknown>,
52
+ ): Record<string, unknown> {
53
+ const target = resolveTarget(file);
54
+ const lock = path.join(path.dirname(target), `.${path.basename(target)}.write.lock`);
55
+ const deadline = performance.now() + 500;
56
+ let fd: number;
57
+ for (;;) {
58
+ try {
59
+ fd = fs.openSync(lock, "wx", 0o600);
60
+ break;
61
+ } catch (error) {
62
+ if (errorCode(error) !== "EEXIST") throw error;
63
+ if (performance.now() >= deadline) {
64
+ // Never steal a lock from a paused writer. After a crash, remove it only
65
+ // after confirming the owner recorded inside the lock is no longer running.
66
+ throw new Error(`Settings write lock is busy: ${lock}`);
67
+ }
68
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
69
+ }
70
+ }
71
+ try {
72
+ fs.writeFileSync(fd, `${process.pid}\n`, "utf8");
73
+ const { document, mode } = readSettings(target);
74
+ const next = update(document);
75
+ publish(target, next, mode);
76
+ return next;
77
+ } finally {
78
+ try { fs.closeSync(fd); } finally { fs.unlinkSync(lock); }
79
+ }
80
+ }
@@ -0,0 +1,102 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFile } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { test } from "node:test";
8
+ import { writeUsageConfig } from "../config.ts";
9
+ import { updateSettingsFile } from "../settings-file.ts";
10
+
11
+ const exec = promisify(execFile);
12
+ const moduleUrl = new URL("../settings-file.ts", import.meta.url).href;
13
+
14
+ function scratch() {
15
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "provider-settings-"));
16
+ return { directory, file: path.join(directory, "settings.json"), clean: () => fs.rmSync(directory, { recursive: true, force: true }) };
17
+ }
18
+
19
+ test("independent processes merge changes into the same settings document", async () => {
20
+ const { directory, file, clean } = scratch();
21
+ try {
22
+ const long = "x".repeat(64 * 1024);
23
+ updateSettingsFile(file, () => ({ untouched: long }));
24
+ const script = `
25
+ import { updateSettingsFile } from ${JSON.stringify(moduleUrl)};
26
+ const [file, field] = process.argv.slice(1);
27
+ updateSettingsFile(file, current => {
28
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
29
+ return { ...current, [field]: true };
30
+ });
31
+ `;
32
+ const commands = ["session", "account", "glyphs"].map((field) =>
33
+ exec(process.execPath, ["--input-type=module", "--eval", script, file, field], { timeout: 3000 }),
34
+ );
35
+ const results = await Promise.allSettled(commands);
36
+ for (const result of results) if (result.status === "rejected") throw result.reason;
37
+ assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")), { untouched: long, session: true, account: true, glyphs: true });
38
+ assert.deepEqual(fs.readdirSync(directory), ["settings.json"]);
39
+ } finally {
40
+ clean();
41
+ }
42
+ });
43
+
44
+ test("an open reader keeps its old snapshot and a symlink still points at the updated target", { skip: process.platform === "win32" }, () => {
45
+ const { directory, file, clean } = scratch();
46
+ try {
47
+ fs.writeFileSync(file, JSON.stringify({ old: "x".repeat(4_096) }));
48
+ fs.chmodSync(file, 0o640);
49
+ const alias = path.join(directory, "alias.json");
50
+ fs.symlinkSync("settings.json", alias);
51
+ const fd = fs.openSync(file, "r");
52
+ try {
53
+ updateSettingsFile(alias, () => ({ next: true }));
54
+ assert.equal(JSON.parse(fs.readFileSync(fd, "utf8")).old.length, 4_096);
55
+ } finally {
56
+ fs.closeSync(fd);
57
+ }
58
+ assert.deepEqual(JSON.parse(fs.readFileSync(alias, "utf8")), { next: true });
59
+ assert.equal(fs.readlinkSync(alias), "settings.json");
60
+ assert.equal(fs.statSync(file).mode & 0o777, 0o640);
61
+ } finally {
62
+ clean();
63
+ }
64
+ });
65
+
66
+ test("invalid existing JSON is not overwritten and the lock is released", () => {
67
+ const { directory, file, clean } = scratch();
68
+ try {
69
+ fs.writeFileSync(file, "{partial");
70
+ assert.throws(() => updateSettingsFile(file, () => ({ next: true })), SyntaxError);
71
+ assert.equal(fs.readFileSync(file, "utf8"), "{partial");
72
+ assert.deepEqual(fs.readdirSync(directory), ["settings.json"]);
73
+ fs.writeFileSync(file, "{}");
74
+ assert.deepEqual(updateSettingsFile(file, () => ({ next: true })), { next: true });
75
+ } finally {
76
+ clean();
77
+ }
78
+ });
79
+
80
+ test("usage changes preserve other settings and refuse invalid config", () => {
81
+ const { directory, clean } = scratch();
82
+ const originalAgentDir = process.env.PI_CODING_AGENT_DIR;
83
+ process.env.PI_CODING_AGENT_DIR = directory;
84
+ try {
85
+ const file = path.join(directory, "opencode-go-provider.json");
86
+ const existing = { usage: { manual: true }, unrelated: { keep: true } };
87
+ fs.writeFileSync(file, JSON.stringify(existing));
88
+ assert.equal(writeUsageConfig({ glyphs: "ascii" }), true);
89
+ assert.equal(writeUsageConfig({ enabled: false }), true);
90
+ assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")), {
91
+ ...existing,
92
+ usage: { ...existing.usage, glyphs: "ascii", enabled: false },
93
+ });
94
+ fs.writeFileSync(file, "{partial");
95
+ assert.equal(writeUsageConfig({ enabled: false }), false);
96
+ assert.equal(fs.readFileSync(file, "utf8"), "{partial");
97
+ } finally {
98
+ if (originalAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
99
+ else process.env.PI_CODING_AGENT_DIR = originalAgentDir;
100
+ clean();
101
+ }
102
+ });