@cortexkit/opencode-openai-auth 1.14.1 → 1.15.0

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 (87) hide show
  1. package/dist/bin.js +9 -9
  2. package/dist/{codex-request-Cl6zEfsR.d.ts → codex-request-DYqSE0ti.d.ts} +373 -2
  3. package/dist/{index-wma2ggn9.js → index-14x5shtc.js} +2 -2
  4. package/dist/index-1wcg7g9d.js +2 -0
  5. package/dist/index-50p400eg.js +8 -0
  6. package/dist/index-98q3mydm.js +64 -0
  7. package/dist/{index-yygzbxjk.js → index-bhkycxbm.js} +1 -1
  8. package/dist/{index-k5av4j8p.js → index-dzpjz8hv.js} +2 -2
  9. package/dist/{index-cxnrd85v.js → index-f7kmsdfk.js} +1 -1
  10. package/dist/{index-z9cj13z7.js → index-hnfqppx9.js} +1 -1
  11. package/dist/{index-2f330s35.js → index-m8m7rakq.js} +2 -2
  12. package/dist/index-mjsmvmt4.js +76 -0
  13. package/dist/{index-gkye2xh1.js → index-s8ghhc9z.js} +2 -2
  14. package/dist/{index-94b345dw.js → index-t65axpta.js} +1 -1
  15. package/dist/index-xjtbg7sx.js +101 -0
  16. package/dist/index.d.ts +1 -372
  17. package/dist/index.js +1 -1
  18. package/dist/openai-auth.schema.json +400 -0
  19. package/dist/rpc/port-file.js +1 -1
  20. package/dist/rpc/protocol.js +1 -1
  21. package/dist/rpc/rpc-client.js +1 -1
  22. package/dist/rpc/rpc-dir.js +1 -1
  23. package/dist/sidebar-state.js +1 -1
  24. package/dist/{token-sgwxn4xg.js → token-j34j1zhm.js} +1 -1
  25. package/dist/token-util-bf619nmg.js +1 -0
  26. package/dist/tui-preferences.js +3 -3
  27. package/dist/v2/server.d.ts +1 -1
  28. package/dist/v2/server.js +2 -2
  29. package/package.json +3 -3
  30. package/src/tui-compiled/raw/logger.js +8 -1
  31. package/src/tui-compiled/raw/shared/061e741c052de9c1-paths.js +48 -0
  32. package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +41 -18
  33. package/src/tui-compiled/raw/shared/23300c068d0b2ffc-parse.js +65 -0
  34. package/src/tui-compiled/raw/shared/3000be4f79f20eb6-write.js +88 -0
  35. package/src/tui-compiled/raw/shared/44449e891fab9fbc-edit.js +229 -0
  36. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +1 -1
  37. package/src/tui-compiled/raw/shared/5803fadb30af0ec0-descriptors.js +81 -0
  38. package/src/tui-compiled/raw/shared/58bc35a3cd459085-define.js +52 -0
  39. package/src/tui-compiled/raw/shared/5f4bc45522ab9bc6-update.js +139 -0
  40. package/src/tui-compiled/raw/shared/6948d70969aa7a55-fs.js +19 -0
  41. package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +28 -12
  42. package/src/tui-compiled/raw/shared/81758f9fe7c2a576-handle.js +228 -0
  43. package/src/tui-compiled/raw/shared/87f6e22d4fc34918-resolve.js +51 -0
  44. package/src/tui-compiled/raw/shared/8a18abe4fa2977c8-menu.js +1 -0
  45. package/src/tui-compiled/raw/shared/8ab1f5794e677151-move.js +351 -0
  46. package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +9 -5
  47. package/src/tui-compiled/raw/shared/9865a4fa45882c6f-settings-decisions.js +13 -0
  48. package/src/tui-compiled/raw/shared/cc0f2d1963547799-index.js +7 -0
  49. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +48 -5
  50. package/src/tui-compiled/raw/shared/e0ed4a490e4eaa4f-schema.js +81 -0
  51. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +146 -2
  52. package/src/tui-compiled/raw/shared/eac0bed49f3d4110-lock-errors.js +15 -0
  53. package/src/tui-compiled/raw/shared/facfd8afc431d68a-refusal.js +15 -0
  54. package/src/tui-compiled/raw/shared/fc7db0c5aa764565-settings-install.js +85 -0
  55. package/src/tui-compiled/raw/shared/fcd26e77bc538838-snapshot.js +150 -0
  56. package/src/tui-compiled/runtime/logger.js +8 -1
  57. package/src/tui-compiled/runtime/shared/061e741c052de9c1-paths.js +48 -0
  58. package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +41 -18
  59. package/src/tui-compiled/runtime/shared/23300c068d0b2ffc-parse.js +65 -0
  60. package/src/tui-compiled/runtime/shared/3000be4f79f20eb6-write.js +88 -0
  61. package/src/tui-compiled/runtime/shared/44449e891fab9fbc-edit.js +229 -0
  62. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +1 -1
  63. package/src/tui-compiled/runtime/shared/5803fadb30af0ec0-descriptors.js +81 -0
  64. package/src/tui-compiled/runtime/shared/58bc35a3cd459085-define.js +52 -0
  65. package/src/tui-compiled/runtime/shared/5f4bc45522ab9bc6-update.js +139 -0
  66. package/src/tui-compiled/runtime/shared/6948d70969aa7a55-fs.js +19 -0
  67. package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +28 -12
  68. package/src/tui-compiled/runtime/shared/81758f9fe7c2a576-handle.js +228 -0
  69. package/src/tui-compiled/runtime/shared/87f6e22d4fc34918-resolve.js +51 -0
  70. package/src/tui-compiled/runtime/shared/8a18abe4fa2977c8-menu.js +1 -0
  71. package/src/tui-compiled/runtime/shared/8ab1f5794e677151-move.js +351 -0
  72. package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +9 -5
  73. package/src/tui-compiled/runtime/shared/9865a4fa45882c6f-settings-decisions.js +13 -0
  74. package/src/tui-compiled/runtime/shared/cc0f2d1963547799-index.js +7 -0
  75. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +48 -5
  76. package/src/tui-compiled/runtime/shared/e0ed4a490e4eaa4f-schema.js +81 -0
  77. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +146 -2
  78. package/src/tui-compiled/runtime/shared/eac0bed49f3d4110-lock-errors.js +15 -0
  79. package/src/tui-compiled/runtime/shared/facfd8afc431d68a-refusal.js +15 -0
  80. package/src/tui-compiled/runtime/shared/fc7db0c5aa764565-settings-install.js +85 -0
  81. package/src/tui-compiled/runtime/shared/fcd26e77bc538838-snapshot.js +150 -0
  82. package/dist/index-3mbw88h7.js +0 -91
  83. package/dist/index-999nwa9p.js +0 -76
  84. package/dist/index-pc4vrrex.js +0 -2
  85. package/dist/index-snq7bwr6.js +0 -8
  86. package/dist/index-xk7f1aef.js +0 -64
  87. package/dist/token-util-8mrnmkge.js +0 -1
@@ -18,8 +18,11 @@ function canonicalPath(file) {
18
18
  return parent === path ? path : join(canonicalPath(parent), basename(path));
19
19
  }
20
20
  }
21
- function identity(info) {
22
- return info && `${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
21
+ function identity(info, settings) {
22
+ if (!info)
23
+ return null;
24
+ const value = `${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
25
+ return settings ? `${value}:${info.ctimeMs}` : value;
23
26
  }
24
27
  /**
25
28
  * Share one directory watcher and metadata poll per canonical path, including
@@ -30,16 +33,25 @@ function identity(info) {
30
33
  * disposable. The last unsubscribe stops both the native watcher and the poll.
31
34
  */
32
35
  export function watchTuiPreferences(file, onChange, options = {}) {
36
+ return watchFile(file, onChange, options, false);
37
+ }
38
+ /** @internal Settings use ordinary reads and observe removal of the user path. */
39
+ export function watchSettings(file, onChange, options = {}) {
40
+ return watchFile(file, onChange, options, true);
41
+ }
42
+ function watchFile(file, onChange, options, settings) {
33
43
  const globals = globalThis;
34
- const key = Symbol.for('cortexkit.common-auth.tui-prefs.watchers.v1');
44
+ const key = Symbol.for(settings
45
+ ? 'cortexkit.common-auth.settings.watchers.v1'
46
+ : 'cortexkit.common-auth.tui-prefs.watchers.v1');
35
47
  const registry = globals[key] ?? new Map();
36
48
  globals[key] = registry;
37
- const path = canonicalPath(file);
49
+ const path = settings ? resolve(file) : canonicalPath(file);
38
50
  const shared = registry.get(path);
39
51
  if (shared)
40
52
  return shared.subscribe(onChange);
41
53
  const name = basename(path);
42
- const read = windowsPrivateFiles
54
+ const read = windowsPrivateFiles && !settings
43
55
  ? (file) => readPrivateText(file)
44
56
  : (options.fs?.readFile ?? ((file) => readFile(file, 'utf8')));
45
57
  const probe = options.fs?.stat ?? stat;
@@ -50,9 +62,9 @@ export function watchTuiPreferences(file, onChange, options = {}) {
50
62
  // Seed synchronously so an immediate write cannot be absorbed as the baseline.
51
63
  // The metadata is recorded only together with contents that were read, as in
52
64
  // the probe below: if the first read fails, the probe keeps trying.
53
- if (!windowsPrivateFiles)
65
+ if (settings || !windowsPrivateFiles)
54
66
  try {
55
- const metadata = identity((options.fs?.statSync ?? statSync)(path));
67
+ const metadata = identity((options.fs?.statSync ?? statSync)(path), settings);
56
68
  lastSeen = (options.fs?.readFileSync ?? ((file) => readFileSync(file, 'utf8')))(path);
57
69
  lastMetadata = metadata;
58
70
  }
@@ -61,19 +73,39 @@ export function watchTuiPreferences(file, onChange, options = {}) {
61
73
  }
62
74
  let disposed = false;
63
75
  const subscribers = new Set();
76
+ const notifySubscribers = () => {
77
+ for (const subscriber of [...subscribers]) {
78
+ if (!subscribers.has(subscriber))
79
+ continue;
80
+ try {
81
+ subscriber.notify();
82
+ }
83
+ catch {
84
+ // A broken subscriber must not prevent the others from observing a change.
85
+ }
86
+ }
87
+ };
64
88
  let checking = Promise.resolve();
65
89
  const checkForChange = (native) => {
66
90
  // Serialize native and poll checks so an older read cannot roll back state.
67
91
  checking = checking.then(async () => {
68
92
  if (disposed)
69
93
  return;
70
- const metadata = identity(await probe(path).catch(() => null));
94
+ const metadata = identity(await probe(path).catch(() => null), settings);
95
+ if (disposed)
96
+ return;
71
97
  if (!native && metadata === lastMetadata)
72
98
  return;
73
99
  // A missing file has nothing to read; remember that so the probe stays
74
100
  // quiet until it reappears.
75
101
  if (metadata === null) {
102
+ const disappeared = lastMetadata !== null;
76
103
  lastMetadata = null;
104
+ if (settings && disappeared) {
105
+ // Dropping the bytes makes recreation observable even with the old text.
106
+ lastSeen = null;
107
+ notifySubscribers();
108
+ }
77
109
  return;
78
110
  }
79
111
  const text = await read(path).catch((error) => {
@@ -96,16 +128,7 @@ export function watchTuiPreferences(file, onChange, options = {}) {
96
128
  if (text === lastSeen)
97
129
  return;
98
130
  lastSeen = text;
99
- for (const subscriber of [...subscribers]) {
100
- if (!subscribers.has(subscriber))
101
- continue;
102
- try {
103
- subscriber.notify();
104
- }
105
- catch {
106
- // A broken subscriber must not prevent the others from observing a change.
107
- }
108
- }
131
+ notifySubscribers();
109
132
  });
110
133
  return checking;
111
134
  };
@@ -0,0 +1,65 @@
1
+ import { parseTree } from "jsonc-parser";
2
+ /** Define own data properties so JSON keys never invoke prototype setters. */
3
+ export function defineSettingsKey(target, key, value) {
4
+ Object.defineProperty(target, key, {
5
+ value,
6
+ enumerable: true,
7
+ writable: true,
8
+ configurable: true,
9
+ });
10
+ }
11
+ /** Convert in document order, retaining the last occurrence of a repeated key. */
12
+ export function settingsValueFromTree(node, onDuplicate = () => { }, keyPath = []) {
13
+ if (node.type === 'object') {
14
+ const value = {};
15
+ for (const property of node.children ?? []) {
16
+ const [keyNode, valueNode] = property.children ?? [];
17
+ if (!keyNode || !valueNode)
18
+ continue;
19
+ const key = keyNode.value;
20
+ const path = [...keyPath, key];
21
+ if (Object.hasOwn(value, key))
22
+ onDuplicate(path);
23
+ defineSettingsKey(value, key, settingsValueFromTree(valueNode, onDuplicate, path));
24
+ }
25
+ return value;
26
+ }
27
+ if (node.type === 'array') {
28
+ return (node.children ?? []).map((child, index) => settingsValueFromTree(child, onDuplicate, [...keyPath, String(index)]));
29
+ }
30
+ return node.value;
31
+ }
32
+ export function parseSettings(source) {
33
+ const hasBom = source.startsWith('\uFEFF');
34
+ const text = hasBom ? source.slice(1) : source;
35
+ // Do not use trim(): it would silently discard a second or misplaced BOM.
36
+ if (/^[\x20\t\r\n]*$/.test(text)) {
37
+ return {
38
+ parseable: true,
39
+ text,
40
+ hasBom,
41
+ tree: undefined,
42
+ value: {},
43
+ duplicateKeyPaths: [],
44
+ hasDuplicates: false,
45
+ };
46
+ }
47
+ const errors = [];
48
+ const tree = parseTree(text, errors, { allowTrailingComma: true });
49
+ if (errors.length || tree?.type !== 'object') {
50
+ return { parseable: false, text, hasBom, tree, errors };
51
+ }
52
+ const paths = new Map();
53
+ const value = settingsValueFromTree(tree, (path) => {
54
+ paths.set(JSON.stringify(path), path);
55
+ });
56
+ return {
57
+ parseable: true,
58
+ text,
59
+ hasBom,
60
+ tree,
61
+ value,
62
+ duplicateKeyPaths: [...paths.values()],
63
+ hasDuplicates: paths.size > 0,
64
+ };
65
+ }
@@ -0,0 +1,88 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { SettingsFs } from "./6948d70969aa7a55-fs.js";
3
+ import { SettingsRefusal } from "./facfd8afc431d68a-refusal.js";
4
+ let stepHook;
5
+ const HARD_LINK_UNSUPPORTED = new Set([
6
+ 'EPERM',
7
+ 'ENOTSUP',
8
+ 'EOPNOTSUPP',
9
+ 'ENOSYS',
10
+ ]);
11
+ /** Internal test hook, deliberately absent from the package entry point. */
12
+ export function setSettingsWriteStepHookForTest(hook) {
13
+ stepHook = hook;
14
+ }
15
+ /** Publish already validated edits while the caller holds the target's lock. */
16
+ export async function writeSettings(options) {
17
+ const { target, text, hasBom, existingMode, lock, logger } = options;
18
+ const platform = options.platform ?? process.platform;
19
+ const temp = `${target}.${randomUUID()}.tmp`;
20
+ let staged = false;
21
+ let published = false;
22
+ try {
23
+ const file = await SettingsFs.open(temp, 'wx', 0o644);
24
+ staged = true;
25
+ try {
26
+ await file.writeFile(`${hasBom ? '\uFEFF' : ''}${text}`, 'utf8');
27
+ if (platform !== 'win32' && existingMode !== undefined) {
28
+ await file.chmod(existingMode & 0o777);
29
+ }
30
+ await file.sync();
31
+ }
32
+ finally {
33
+ await file.close();
34
+ }
35
+ await stepHook?.('staged', { target, temp });
36
+ await lock.assertOwned();
37
+ if (existingMode !== undefined) {
38
+ try {
39
+ await SettingsFs.rename(temp, target);
40
+ }
41
+ catch (error) {
42
+ if (platform === 'win32' &&
43
+ ['EPERM', 'EACCES', 'EBUSY'].includes(error.code ?? '')) {
44
+ throw new SettingsRefusal('settings-busy', `Settings file is busy: ${target}`, { cause: error });
45
+ }
46
+ throw error;
47
+ }
48
+ published = true;
49
+ }
50
+ else {
51
+ try {
52
+ // A hard link never replaces a file created since the locked read.
53
+ await SettingsFs.link(temp, target);
54
+ }
55
+ catch (error) {
56
+ const code = error.code ?? '';
57
+ if (code === 'EEXIST') {
58
+ throw new SettingsRefusal('settings-busy', `Settings file appeared before publication: ${target}`, { cause: error });
59
+ }
60
+ // Some filesystems (FAT, exFAT, some network and user-space mounts) have no
61
+ // hard links. A non-atomic create could expose a half-written file, so
62
+ // refuse instead of falling back.
63
+ if (HARD_LINK_UNSUPPORTED.has(code)) {
64
+ throw new SettingsRefusal('settings-unavailable', `Settings file cannot be created on this filesystem: ${target}`, { cause: error });
65
+ }
66
+ throw error;
67
+ }
68
+ published = true;
69
+ try {
70
+ await SettingsFs.unlink(temp);
71
+ }
72
+ catch (error) {
73
+ // Publication succeeded; an orphaned temp must not turn it into a refusal.
74
+ logger?.warn('Settings temp cleanup failed after publication', {
75
+ target,
76
+ temp,
77
+ error,
78
+ });
79
+ }
80
+ }
81
+ return { outcome: 'updated' };
82
+ }
83
+ finally {
84
+ if (staged && !published) {
85
+ await SettingsFs.unlink(temp).catch(() => { });
86
+ }
87
+ }
88
+ }
@@ -0,0 +1,229 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { applyEdits, createScanner, findNodeAtLocation, modify, } from "jsonc-parser";
3
+ import { isJsonObject, validateValue, } from "./5803fadb30af0ec0-descriptors.js";
4
+ import { parseSettings } from "./23300c068d0b2ffc-parse.js";
5
+ import { SettingsRefusal } from "./facfd8afc431d68a-refusal.js";
6
+ // jsonc-parser declares these scanner tokens as an ambient const enum, which
7
+ // cannot be imported as a value with verbatimModuleSyntax enabled.
8
+ const SyntaxKind = {
9
+ CommaToken: 5,
10
+ LineCommentTrivia: 12,
11
+ BlockCommentTrivia: 13,
12
+ Trivia: 15,
13
+ EOF: 17,
14
+ };
15
+ function invalid() {
16
+ throw new SettingsRefusal('settings-invalid-value', 'The settings edit does not match its declared value');
17
+ }
18
+ function parseForEdit(text) {
19
+ const parsed = parseSettings(text);
20
+ if (!parsed.parseable || parsed.hasDuplicates) {
21
+ throw new SettingsRefusal('settings-unparseable', 'Settings must be an object without duplicate keys');
22
+ }
23
+ return parsed;
24
+ }
25
+ function descriptorAtPath(descriptor, path) {
26
+ let current = descriptor;
27
+ for (const key of path) {
28
+ if (current.kind === 'object' && Object.hasOwn(current.fields, key)) {
29
+ current = current.fields[key];
30
+ }
31
+ else if (current.kind === 'record') {
32
+ current = current.value;
33
+ }
34
+ else {
35
+ invalid();
36
+ }
37
+ }
38
+ return current;
39
+ }
40
+ function destination(declaration, setting, value, { host, model }) {
41
+ if (declaration.overrides !== undefined && isJsonObject(value)) {
42
+ if (declaration.overrides.model &&
43
+ model !== undefined &&
44
+ model !== 'default' &&
45
+ model !== 'opencode' &&
46
+ model !== 'pi' &&
47
+ Object.hasOwn(value, model)) {
48
+ return [setting, model];
49
+ }
50
+ if (declaration.overrides.host &&
51
+ (host === 'opencode' || host === 'pi') &&
52
+ Object.hasOwn(value, host)) {
53
+ return [setting, host];
54
+ }
55
+ return [setting, 'default'];
56
+ }
57
+ return [setting];
58
+ }
59
+ function resolutionUnit(descriptor, destination, path) {
60
+ let current = descriptor;
61
+ const unitPath = [...destination];
62
+ for (const key of path) {
63
+ // Records and lists resolve whole, even when the edit changes one leaf.
64
+ if (current.kind === 'record' || current.kind === 'list')
65
+ break;
66
+ current = descriptorAtPath(current, [key]);
67
+ unitPath.push(key);
68
+ }
69
+ return { path: unitPath, descriptor: current };
70
+ }
71
+ function checkPath(parsed, path) {
72
+ for (let length = 1; length < path.length; length++) {
73
+ const node = parsed.tree && findNodeAtLocation(parsed.tree, path.slice(0, length));
74
+ if (node && node.type !== 'object')
75
+ invalid();
76
+ }
77
+ }
78
+ /** Remove only the member's own tokens; intervening comment lines belong to neither neighbor. */
79
+ function removeMember(text, tree, path) {
80
+ const property = tree && findNodeAtLocation(tree, path)?.parent;
81
+ const parent = property?.parent;
82
+ if (property?.type !== 'property' || !parent?.children)
83
+ return text;
84
+ const scanner = createScanner(text, false);
85
+ const end = property.offset + property.length;
86
+ const index = parent.children.indexOf(property);
87
+ const next = parent.children[index + 1];
88
+ const followingEnd = next?.offset ?? parent.offset + parent.length - 1;
89
+ let comma;
90
+ scanner.setPosition(end);
91
+ while (scanner.getPosition() < followingEnd) {
92
+ const token = scanner.scan();
93
+ if (token === SyntaxKind.CommaToken) {
94
+ comma = { start: scanner.getTokenOffset(), end: scanner.getPosition() };
95
+ break;
96
+ }
97
+ if (token === SyntaxKind.EOF)
98
+ break;
99
+ }
100
+ if (!comma && index > 0) {
101
+ const previous = parent.children[index - 1];
102
+ scanner.setPosition(previous.offset + previous.length);
103
+ while (scanner.getPosition() < property.offset) {
104
+ const token = scanner.scan();
105
+ if (token === SyntaxKind.CommaToken) {
106
+ comma = { start: scanner.getTokenOffset(), end: scanner.getPosition() };
107
+ break;
108
+ }
109
+ if (token === SyntaxKind.EOF)
110
+ break;
111
+ }
112
+ }
113
+ let removeEnd = end;
114
+ scanner.setPosition(end);
115
+ while (scanner.getPosition() < followingEnd) {
116
+ const token = scanner.scan();
117
+ if (token === SyntaxKind.Trivia || token === SyntaxKind.CommaToken)
118
+ continue;
119
+ if (token !== SyntaxKind.LineCommentTrivia &&
120
+ token !== SyntaxKind.BlockCommentTrivia)
121
+ break;
122
+ removeEnd = scanner.getPosition();
123
+ // A multiline trailing comment belongs to the member, but comments starting
124
+ // on subsequent lines do not.
125
+ if (/[\r\n]/.test(scanner.getTokenValue()))
126
+ break;
127
+ }
128
+ if (comma &&
129
+ comma.start >= end &&
130
+ !/[\r\n]/.test(text.slice(end, comma.start))) {
131
+ removeEnd = Math.max(removeEnd, comma.end);
132
+ }
133
+ const lineStart = Math.max(text.lastIndexOf('\n', property.offset - 1), text.lastIndexOf('\r', property.offset - 1)) + 1;
134
+ let removeStart = property.offset;
135
+ const lineBreak = /^[\t ]*(\r\n|\r|\n)/.exec(text.slice(removeEnd));
136
+ if (/^[\t ]*$/.test(text.slice(lineStart, property.offset)) && lineBreak) {
137
+ removeStart = lineStart;
138
+ removeEnd += lineBreak[0].length;
139
+ }
140
+ const edits = [
141
+ { offset: removeStart, length: removeEnd - removeStart, content: '' },
142
+ ];
143
+ // The last member's comma can be separated from it by preserved comment lines.
144
+ if (comma && (comma.start < removeStart || comma.start >= removeEnd)) {
145
+ edits.push({
146
+ offset: comma.start,
147
+ length: comma.end - comma.start,
148
+ content: '',
149
+ });
150
+ }
151
+ return applyEdits(text, edits);
152
+ }
153
+ /** Pure JSONC edit engine; the writer restores the BOM and owns durable I/O. */
154
+ export function applySettingsEdits(definition, source, edits, context) {
155
+ // Validate the entire request before changing even the private working text.
156
+ for (const edit of edits) {
157
+ if (!Object.hasOwn(definition.settings, edit.setting))
158
+ invalid();
159
+ const declaration = definition.settings[edit.setting];
160
+ if (edit.path !== undefined &&
161
+ declaration.value.kind !== 'object' &&
162
+ declaration.value.kind !== 'record')
163
+ invalid();
164
+ const descriptor = descriptorAtPath(declaration.value, edit.path ?? []);
165
+ if (edit.remove !== true && !validateValue(descriptor, edit.value))
166
+ invalid();
167
+ }
168
+ const start = parseForEdit(source);
169
+ let working = start;
170
+ const units = [];
171
+ for (const edit of edits) {
172
+ const declaration = definition.settings[edit.setting];
173
+ const base = edit.path !== undefined
174
+ ? [edit.setting]
175
+ : destination(declaration, edit.setting, working.value[edit.setting], context);
176
+ const path = [...base, ...(edit.path ?? [])];
177
+ checkPath(working, path);
178
+ units.push(resolutionUnit(declaration.value, base, edit.path ?? []));
179
+ const node = working.tree && findNodeAtLocation(working.tree, path);
180
+ let text;
181
+ if (edit.remove === true) {
182
+ if (!node)
183
+ continue;
184
+ text = removeMember(working.text, working.tree, path);
185
+ let removed = parseForEdit(text);
186
+ const remaining = removed.value[edit.setting];
187
+ if (base.length === 2 &&
188
+ isJsonObject(remaining) &&
189
+ Object.keys(remaining).length === 0) {
190
+ text = removeMember(text, removed.tree, [edit.setting]);
191
+ removed = parseForEdit(text);
192
+ }
193
+ working = removed;
194
+ }
195
+ else {
196
+ if (node && isDeepStrictEqual(valueAt(working.value, path), edit.value))
197
+ continue;
198
+ text = applyEdits(working.text, modify(working.text, path, edit.value, {
199
+ formattingOptions: { insertSpaces: true, tabSize: 2 },
200
+ }));
201
+ working = parseForEdit(text);
202
+ }
203
+ }
204
+ for (const unit of units) {
205
+ const node = working.tree && findNodeAtLocation(working.tree, unit.path);
206
+ if (node &&
207
+ !validateValue(unit.descriptor, valueAt(working.value, unit.path), {
208
+ allowUnknownFields: true,
209
+ }))
210
+ invalid();
211
+ }
212
+ if (isDeepStrictEqual(start.value, working.value)) {
213
+ return { outcome: 'unchanged', text: start.text, hasBom: start.hasBom };
214
+ }
215
+ return {
216
+ outcome: 'updated',
217
+ text: working.text,
218
+ hasBom: start.hasBom,
219
+ };
220
+ }
221
+ function valueAt(value, path) {
222
+ let current = value;
223
+ for (const key of path) {
224
+ if (!isJsonObject(current) || !Object.hasOwn(current, key))
225
+ return undefined;
226
+ current = current[key];
227
+ }
228
+ return current;
229
+ }
@@ -21,7 +21,7 @@ export class LockOwnershipError extends Error {
21
21
  this.details = details;
22
22
  }
23
23
  }
24
- function isChangingLockRecord(error, target, name) {
24
+ export function isChangingLockRecord(error, target, name) {
25
25
  const path = resolve(lockPathFor(target, name));
26
26
  const paths = [path, join(path, 'owner.json')];
27
27
  return (((isWindowsSharingViolation(error) ||
@@ -0,0 +1,81 @@
1
+ export function boolean() {
2
+ return Object.freeze({ kind: 'boolean' });
3
+ }
4
+ export function integer({ min, max } = {}) {
5
+ return Object.freeze({ kind: 'integer', min, max });
6
+ }
7
+ export function number({ min, max } = {}) {
8
+ return Object.freeze({ kind: 'number', min, max });
9
+ }
10
+ export function string() {
11
+ return Object.freeze({ kind: 'string' });
12
+ }
13
+ export function oneOf(values) {
14
+ return Object.freeze({
15
+ kind: 'oneOf',
16
+ values: Object.freeze([...values]),
17
+ });
18
+ }
19
+ export function list(item) {
20
+ return deepFreeze({ kind: 'list', item });
21
+ }
22
+ export function object(fields) {
23
+ return deepFreeze({ kind: 'object', fields: { ...fields } });
24
+ }
25
+ export function record(value) {
26
+ return deepFreeze({ kind: 'record', value });
27
+ }
28
+ /** JSON objects exclude arrays and objects such as Date that serialize differently. */
29
+ export function isJsonObject(value) {
30
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
31
+ return false;
32
+ }
33
+ const prototype = Object.getPrototypeOf(value);
34
+ return prototype === Object.prototype || prototype === null;
35
+ }
36
+ /** Missing fields can be filled from lower levels, but list and record objects must be complete. */
37
+ export function validateValue(descriptor, value, options = {}) {
38
+ switch (descriptor.kind) {
39
+ case 'boolean':
40
+ return typeof value === 'boolean';
41
+ case 'integer':
42
+ case 'number':
43
+ return (typeof value === 'number' &&
44
+ Number.isFinite(value) &&
45
+ (descriptor.kind !== 'integer' || Number.isInteger(value)) &&
46
+ (descriptor.min === undefined || value >= descriptor.min) &&
47
+ (descriptor.max === undefined || value <= descriptor.max));
48
+ case 'string':
49
+ return typeof value === 'string';
50
+ case 'oneOf':
51
+ return typeof value === 'string' && descriptor.values.includes(value);
52
+ case 'list':
53
+ return (Array.isArray(value) &&
54
+ Array.from(value).every((item) => validateValue(descriptor.item, item, {
55
+ ...options,
56
+ completeObjects: true,
57
+ })));
58
+ case 'object':
59
+ return (isJsonObject(value) &&
60
+ Object.entries(value).every(([key, field]) => Object.hasOwn(descriptor.fields, key)
61
+ ? validateValue(descriptor.fields[key], field, options)
62
+ : options.allowUnknownFields === true) &&
63
+ (!options.completeObjects ||
64
+ Object.keys(descriptor.fields).every((key) => Object.hasOwn(value, key))));
65
+ case 'record':
66
+ return (isJsonObject(value) &&
67
+ Object.values(value).every((item) => validateValue(descriptor.value, item, {
68
+ ...options,
69
+ completeObjects: true,
70
+ })));
71
+ }
72
+ }
73
+ /** Internal helper; definitions and descriptor payloads are immutable at runtime. */
74
+ export function deepFreeze(value) {
75
+ if (value && typeof value === 'object') {
76
+ for (const child of Object.values(value))
77
+ deepFreeze(child);
78
+ Object.freeze(value);
79
+ }
80
+ return value;
81
+ }
@@ -0,0 +1,52 @@
1
+ import { deepFreeze, isJsonObject, validateValue, } from "./5803fadb30af0ec0-descriptors.js";
2
+ export function defineSettings(definition) {
3
+ for (const [name, declaration] of Object.entries(definition.settings)) {
4
+ if (name === 'schema_version' || name === '$schema') {
5
+ throw new TypeError(`Reserved setting name: ${name}`);
6
+ }
7
+ if (!/^[a-z][a-z0-9_]*$/.test(name) || /\s/.test(name)) {
8
+ throw new TypeError(`Setting name must be snake_case: ${name}`);
9
+ }
10
+ if (name === 'sidebar' && declaration.value.kind !== 'object') {
11
+ throw new TypeError('The sidebar setting must use an object descriptor');
12
+ }
13
+ if (declaration.overrides !== undefined &&
14
+ (declaration.value.kind === 'object' ||
15
+ declaration.value.kind === 'record')) {
16
+ throw new TypeError(`Object and record settings cannot use overrides: ${name}`);
17
+ }
18
+ if (!Object.hasOwn(declaration, 'default') ||
19
+ !validateValue(declaration.value, declaration.default, {
20
+ completeObjects: true,
21
+ })) {
22
+ throw new TypeError(`Invalid default for setting: ${name}`);
23
+ }
24
+ }
25
+ // Copy before freezing so the caller can still use its original default values.
26
+ return deepFreeze({
27
+ plugin: definition.plugin,
28
+ settings: Object.fromEntries(Object.entries(definition.settings).map(([name, declaration]) => [
29
+ name,
30
+ structuredClone({
31
+ ...declaration,
32
+ project: declaration.project ?? 'user-only',
33
+ }),
34
+ ])),
35
+ });
36
+ }
37
+ /** Internal helper: host names are reserved and never count as model ids. */
38
+ export function isOverrideKeyAllowed(overrides, key) {
39
+ if (key === 'default')
40
+ return true;
41
+ if (key === 'opencode' || key === 'pi')
42
+ return overrides.host === true;
43
+ return overrides.model === true;
44
+ }
45
+ /** Validate a file, update or map value, including any permitted override object. */
46
+ export function validateSettingValue(declaration, value, options = {}) {
47
+ if (declaration.overrides !== undefined && isJsonObject(value)) {
48
+ return Object.entries(value).every(([key, entry]) => isOverrideKeyAllowed(declaration.overrides ?? {}, key) &&
49
+ validateValue(declaration.value, entry, options));
50
+ }
51
+ return validateValue(declaration.value, value, options);
52
+ }