noonsight 0.0.0-stage → 0.1.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 (115) hide show
  1. package/.claude-plugin/marketplace.json +19 -0
  2. package/.claude-plugin/plugin.json +14 -0
  3. package/LICENSE +21 -0
  4. package/README.md +281 -2
  5. package/dist/src/adapters/claude-code/classifier.js +138 -0
  6. package/dist/src/adapters/claude-code/code-edit.js +108 -0
  7. package/dist/src/adapters/claude-code/compat.js +31 -0
  8. package/dist/src/adapters/claude-code/definitions.js +347 -0
  9. package/dist/src/adapters/claude-code/fork.js +132 -0
  10. package/dist/src/adapters/claude-code/hook.js +652 -0
  11. package/dist/src/adapters/claude-code/install.js +186 -0
  12. package/dist/src/adapters/claude-code/launch.js +270 -0
  13. package/dist/src/adapters/claude-code/launcher.js +252 -0
  14. package/dist/src/adapters/claude-code/locations.js +115 -0
  15. package/dist/src/adapters/claude-code/managed.js +75 -0
  16. package/dist/src/adapters/claude-code/plugin-files.js +88 -0
  17. package/dist/src/adapters/claude-code/plugins.js +117 -0
  18. package/dist/src/adapters/claude-code/pointer.js +48 -0
  19. package/dist/src/adapters/claude-code/predict.js +271 -0
  20. package/dist/src/adapters/claude-code/routing.js +88 -0
  21. package/dist/src/adapters/claude-code/settings.js +189 -0
  22. package/dist/src/adapters/claude-code/subagents.js +666 -0
  23. package/dist/src/adapters/claude-code/triggers.js +88 -0
  24. package/dist/src/cli.js +157 -0
  25. package/dist/src/commands/accept.js +115 -0
  26. package/dist/src/commands/check.js +529 -0
  27. package/dist/src/commands/hook.js +73 -0
  28. package/dist/src/commands/init.js +29 -0
  29. package/dist/src/commands/install.js +370 -0
  30. package/dist/src/commands/models.js +213 -0
  31. package/dist/src/commands/receives.js +84 -0
  32. package/dist/src/commands/report.js +386 -0
  33. package/dist/src/commands/resolve.js +32 -0
  34. package/dist/src/commands/run.js +168 -0
  35. package/dist/src/commands/trust.js +70 -0
  36. package/dist/src/commands/usage.js +10 -0
  37. package/dist/src/commands/watch.js +154 -0
  38. package/dist/src/config/create.js +51 -0
  39. package/dist/src/config/json-schema.js +207 -0
  40. package/dist/src/config/load.js +758 -0
  41. package/dist/src/config/paths.js +42 -0
  42. package/dist/src/config/preset-changes.js +190 -0
  43. package/dist/src/config/project.js +354 -0
  44. package/dist/src/config/rewrite.js +112 -0
  45. package/dist/src/core/backtracking.js +330 -0
  46. package/dist/src/core/classify.js +66 -0
  47. package/dist/src/core/normalize.js +24 -0
  48. package/dist/src/core/overlap.js +39 -0
  49. package/dist/src/core/regex-sample.js +278 -0
  50. package/dist/src/core/resolve.js +201 -0
  51. package/dist/src/core/route.js +93 -0
  52. package/dist/src/core/scope.js +77 -0
  53. package/dist/src/core/triggers.js +30 -0
  54. package/dist/src/core/types.js +74 -0
  55. package/dist/src/state/agents.js +200 -0
  56. package/dist/src/state/claims.js +80 -0
  57. package/dist/src/state/files.js +84 -0
  58. package/dist/src/state/installs.js +29 -0
  59. package/dist/src/state/log.js +90 -0
  60. package/dist/src/state/node.js +35 -0
  61. package/dist/src/state/sessions.js +109 -0
  62. package/dist/src/state/triggers.js +57 -0
  63. package/dist/src/version.js +24 -0
  64. package/dist/src/watch/service.js +172 -0
  65. package/dist/src/watch/watcher.js +130 -0
  66. package/dist/src/wording.js +11 -0
  67. package/hooks/hooks.json +118 -0
  68. package/package.json +60 -4
  69. package/presets/claude/SOURCES.md +485 -0
  70. package/presets/claude/preset.json +432 -0
  71. package/presets/claude/rules/fable-5-2/code-ownership.md +1 -0
  72. package/presets/claude/rules/fable-5-2/finish-work.md +1 -0
  73. package/presets/claude/rules/fable-5-2/low-context-report.md +1 -0
  74. package/presets/claude/rules/fable-5-2/progress-updates.md +1 -0
  75. package/presets/claude/rules/haiku-5-5/carry-through.md +1 -0
  76. package/presets/claude/rules/haiku-5-5/search-recent-facts.md +1 -0
  77. package/presets/claude/rules/haiku-5-5/verify-changes.md +1 -0
  78. package/presets/claude/rules/opus-5-5/explore-before-acting.md +1 -0
  79. package/presets/claude/rules/opus-5-5/progress-updates.md +1 -0
  80. package/presets/claude/rules/opus-5-5/unattended-run.md +1 -0
  81. package/presets/claude/rules/sonnet-5-5/carry-through.md +1 -0
  82. package/presets/claude/rules/sonnet-5-5/check-current-facts.md +1 -0
  83. package/presets/claude/rules/sonnet-5-5/ideas-first.md +1 -0
  84. package/presets/claude/rules/sonnet-5-5/no-self-review-rounds.md +1 -0
  85. package/presets/claude/rules/sonnet-5-5/stay-in-scope.md +1 -0
  86. package/presets/claude/rules/sonnet-5-5/verify-changes.md +1 -0
  87. package/presets/claude/versions/1.3.0/preset.json +432 -0
  88. package/presets/claude/versions/1.3.0/rules/fable-5-2/code-ownership.md +1 -0
  89. package/presets/claude/versions/1.3.0/rules/fable-5-2/finish-work.md +1 -0
  90. package/presets/claude/versions/1.3.0/rules/fable-5-2/low-context-report.md +1 -0
  91. package/presets/claude/versions/1.3.0/rules/fable-5-2/progress-updates.md +1 -0
  92. package/presets/claude/versions/1.3.0/rules/haiku-5-5/carry-through.md +1 -0
  93. package/presets/claude/versions/1.3.0/rules/haiku-5-5/search-recent-facts.md +1 -0
  94. package/presets/claude/versions/1.3.0/rules/haiku-5-5/verify-changes.md +1 -0
  95. package/presets/claude/versions/1.3.0/rules/opus-5-5/explore-before-acting.md +1 -0
  96. package/presets/claude/versions/1.3.0/rules/opus-5-5/progress-updates.md +1 -0
  97. package/presets/claude/versions/1.3.0/rules/opus-5-5/unattended-run.md +1 -0
  98. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/carry-through.md +1 -0
  99. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/check-current-facts.md +1 -0
  100. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/ideas-first.md +1 -0
  101. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/no-self-review-rounds.md +1 -0
  102. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/stay-in-scope.md +1 -0
  103. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/verify-changes.md +1 -0
  104. package/schema/noonsight-project.schema.json +394 -0
  105. package/schema/noonsight.schema.json +425 -0
  106. package/schema/preset.schema.json +194 -0
  107. package/scripts/noonsight +68 -0
  108. package/skills/accept/SKILL.md +11 -0
  109. package/skills/check/SKILL.md +11 -0
  110. package/skills/models/SKILL.md +11 -0
  111. package/skills/report/SKILL.md +11 -0
  112. package/skills/resolve/SKILL.md +12 -0
  113. package/skills/setup/SKILL.md +15 -0
  114. package/skills/trust/SKILL.md +12 -0
  115. package/skills/untrust/SKILL.md +12 -0
@@ -0,0 +1,186 @@
1
+ // Install and uninstall: write the hook pointer, then add noonsight's hook entries to a settings file
2
+ // (or remove both). Every write replaces a whole file in one step, nothing outside noonsight's own
3
+ // entries is changed, and running the same command twice changes nothing the second time.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { isPermissionError, mkdirWithMode, modeOf, readJsonFile, writeFileAtomic } from '../../state/files.js';
7
+ import { pointerScript, readPointer } from './pointer.js';
8
+ import { HOOK_EVENTS, isObject, withNoonsightHooks, withoutNoonsightHooks, SettingsShapeError } from './settings.js';
9
+ /** A refusal that leaves every file as it was. */
10
+ export class InstallRefused extends Error {
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = 'InstallRefused';
14
+ }
15
+ }
16
+ /** This account cannot write one of the paths; nothing was changed. */
17
+ export class NeedsPermission extends Error {
18
+ paths;
19
+ constructor(paths) {
20
+ super(`cannot write ${paths.join(' and ')}`);
21
+ this.paths = paths;
22
+ this.name = 'NeedsPermission';
23
+ }
24
+ }
25
+ const EVENTS = HOOK_EVENTS.join(', ');
26
+ /** What install would write, after every check that can refuse it; nothing is written. */
27
+ function planInstall(target, runtime) {
28
+ if (target.configDir !== undefined && !isDirectory(target.configDir))
29
+ throw new InstallRefused(`${target.configDir} is not a directory; give the Claude Code configuration directory of an account, such as ~/.claude`);
30
+ refuseRootInAccount(target);
31
+ const settings = readSettings(target.settingsFile);
32
+ const edit = editSettings(target.settingsFile, () => withNoonsightHooks(settings ?? {}, target.pointer));
33
+ const pointer = { ...runtime, kind: target.kind };
34
+ const script = pointerScript(pointer);
35
+ const oldScript = readText(target.pointer);
36
+ const pointerChanged = oldScript !== script;
37
+ const toWrite = [...(pointerChanged ? [target.pointer] : []), ...(edit.changed ? [target.settingsFile] : [])];
38
+ const blocked = toWrite.filter((f) => !canCreate(f));
39
+ if (blocked.length)
40
+ throw new NeedsPermission(blocked);
41
+ return { settings, edit, script, oldScript, pointerChanged };
42
+ }
43
+ /** Throws what install would throw, and writes nothing; for installing into several directories at once. */
44
+ export function checkInstallable(target, runtime) {
45
+ planInstall(target, runtime);
46
+ }
47
+ export function install(target, runtime) {
48
+ const { settings, edit, script, oldScript, pointerChanged } = planInstall(target, runtime);
49
+ if (pointerChanged) {
50
+ mkdirWithMode(path.dirname(target.pointer), 0o755);
51
+ writeFileAtomic(target.pointer, script, 0o755);
52
+ }
53
+ if (edit.changed) {
54
+ try {
55
+ mkdirWithMode(path.dirname(target.settingsFile), 0o755);
56
+ writeFileAtomic(target.settingsFile, `${JSON.stringify(edit.settings, null, 2)}\n`, modeOf(target.settingsFile, 0o644));
57
+ }
58
+ catch (e) {
59
+ // Put the pointer back as it was, so a failed install leaves nothing behind.
60
+ if (pointerChanged) {
61
+ if (oldScript === null)
62
+ fs.rmSync(target.pointer, { force: true });
63
+ else
64
+ writeFileAtomic(target.pointer, oldScript, 0o755);
65
+ }
66
+ throw e;
67
+ }
68
+ }
69
+ return [
70
+ `hook pointer ${target.pointer}: ${pointerChanged ? (oldScript === null ? 'written' : 'rewritten') : 'unchanged'} (runs ${runtime.node} ${runtime.cli})`,
71
+ `hooks ${target.settingsFile}: ${edit.changed ? (settings === null ? 'created' : 'added') : 'unchanged'} (${EVENTS})`,
72
+ ];
73
+ }
74
+ /** What uninstall would write, after every check that can refuse it; nothing is written. */
75
+ function planUninstall(target, options) {
76
+ refuseRootInAccount(target);
77
+ const settings = readSettings(target.settingsFile);
78
+ const edit = settings === null ? null : editSettings(target.settingsFile, () => withoutNoonsightHooks(settings));
79
+ // noonsight's drop-in file is removed once nothing is left in it.
80
+ const removeFile = edit !== null && target.kind === 'managed' && Object.keys(edit.settings).length === 0;
81
+ const pointer = readPointer(target.pointer);
82
+ const removePointer = pointer !== null && pointer.kind === target.kind && !options.keepPointer;
83
+ const toWrite = [...(edit?.changed || removeFile ? [target.settingsFile] : []), ...(removePointer ? [target.pointer] : [])];
84
+ const blocked = toWrite.filter((f) => !canCreate(f));
85
+ if (blocked.length)
86
+ throw new NeedsPermission(blocked);
87
+ return { edit, removeFile, pointer, removePointer };
88
+ }
89
+ /** Throws what uninstall would throw, and writes nothing; for uninstalling from several directories at once. */
90
+ export function checkUninstallable(target, options = {}) {
91
+ planUninstall(target, options);
92
+ }
93
+ export function uninstall(target, options = {}) {
94
+ const { edit, removeFile, pointer, removePointer } = planUninstall(target, options);
95
+ if (removeFile)
96
+ fs.rmSync(target.settingsFile, { force: true });
97
+ else if (edit?.changed)
98
+ writeFileAtomic(target.settingsFile, `${JSON.stringify(edit.settings, null, 2)}\n`, modeOf(target.settingsFile, 0o644));
99
+ if (removePointer)
100
+ fs.rmSync(target.pointer, { force: true });
101
+ const hooksLine = removeFile ? 'removed the file' : edit?.changed ? 'removed' : 'none found';
102
+ const pointerLine = removePointer ? 'removed' : pointer === null ? 'none found' : options.keepPointer ? 'kept (another account install uses it)' : 'kept (not written for this kind of install)';
103
+ return [`hooks ${target.settingsFile}: ${hooksLine}`, `hook pointer ${target.pointer}: ${pointerLine}`];
104
+ }
105
+ /** The parsed settings file, or null when it does not exist. An unreadable file is refused. */
106
+ export function readSettings(file) {
107
+ if (!fs.existsSync(file))
108
+ return null;
109
+ let value;
110
+ try {
111
+ value = readJsonFile(file);
112
+ }
113
+ catch (e) {
114
+ if (isPermissionError(e))
115
+ throw new NeedsPermission([file]);
116
+ throw new InstallRefused(`${file} is not valid JSON (${e.message}); fix it first, nothing was changed`);
117
+ }
118
+ if (!isObject(value))
119
+ throw new InstallRefused(`${file} does not hold a JSON object; fix it first, nothing was changed`);
120
+ return value;
121
+ }
122
+ function editSettings(file, edit) {
123
+ try {
124
+ return edit();
125
+ }
126
+ catch (e) {
127
+ if (e instanceof SettingsShapeError)
128
+ throw new InstallRefused(`${file}: ${e.message}; fix it first, nothing was changed`);
129
+ throw e;
130
+ }
131
+ }
132
+ function readText(file) {
133
+ try {
134
+ return fs.readFileSync(file, 'utf8');
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ }
140
+ /**
141
+ * An administrator writing another account's settings would leave that account a settings file it
142
+ * cannot change any more, so a per-account install runs as the account that owns the directory.
143
+ */
144
+ function refuseRootInAccount(target) {
145
+ if (target.kind !== 'account' || target.configDir === undefined || process.getuid?.() !== 0)
146
+ return;
147
+ let owner;
148
+ try {
149
+ owner = fs.statSync(target.configDir).uid;
150
+ }
151
+ catch {
152
+ return;
153
+ }
154
+ if (owner !== 0)
155
+ throw new InstallRefused(`${target.configDir} belongs to another account; run noonsight with --account as that account, without sudo, so its settings stay its own`);
156
+ }
157
+ function isDirectory(dir) {
158
+ try {
159
+ return fs.statSync(dir).isDirectory();
160
+ }
161
+ catch {
162
+ return false;
163
+ }
164
+ }
165
+ /** Whether this account can create or replace the file: the nearest existing directory above it must be writable. */
166
+ function canCreate(file) {
167
+ let dir = path.dirname(file);
168
+ for (;;) {
169
+ try {
170
+ if (fs.statSync(dir).isDirectory()) {
171
+ fs.accessSync(dir, fs.constants.W_OK);
172
+ return true;
173
+ }
174
+ return false;
175
+ }
176
+ catch (e) {
177
+ if (e.code !== 'ENOENT')
178
+ return false;
179
+ }
180
+ const parent = path.dirname(dir);
181
+ if (parent === dir)
182
+ return false;
183
+ dir = parent;
184
+ }
185
+ }
186
+ //# sourceMappingURL=install.js.map
@@ -0,0 +1,270 @@
1
+ // The model a session was started with, for a SessionStart input that names none, as in every
2
+ // `claude -p` run. Claude Code picks the starting model from, in order
3
+ // (https://code.claude.com/docs/en/model-config, "Setting your model"):
4
+ //
5
+ // 1. the --model argument of the claude command;
6
+ // 2. the ANTHROPIC_MODEL environment variable;
7
+ // 3. the model setting of the highest-ranked settings file that sets one.
8
+ //
9
+ // The hook reads the same three: the command line of the Claude Code process that runs it (its
10
+ // parent), its own environment, which Claude Code passes to hooks with the settings' env applied, and
11
+ // the settings files Claude Code reads. The first source that names a model decides; a lower source
12
+ // is never consulted past it, because Claude Code would not consult it either.
13
+ import { spawnSync } from 'node:child_process';
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { normalizeModel } from '../../core/normalize.js';
17
+ import { MODEL_ALIASES, PROVIDER_VARS, RUNTIME_MODEL_VALUES } from './compat.js';
18
+ import { defaultAccountDir, managedTarget } from './locations.js';
19
+ import { managedFilesApply, readManagedFiles, readRemoteSettings } from './managed.js';
20
+ import { isObject } from './settings.js';
21
+ export function launchModel(ctx, sources = 'all') {
22
+ return launchModelFrom(ctx.commandLine ? ctx.commandLine() : readCommandLine(ctx.pid, ctx.platform ?? process.platform), ctx, sources);
23
+ }
24
+ /**
25
+ * The same choice for a known command line: the Claude Code arguments as the launcher is about to
26
+ * pass them, or null when they cannot be read.
27
+ */
28
+ export function launchModelFrom(cmd, ctx, sources = 'all') {
29
+ if (sources !== 'settings') {
30
+ const flag = cmd ? modelArgument(cmd, ctx.env) : null;
31
+ if (flag !== null)
32
+ return flag;
33
+ const fromEnv = ctx.env.ANTHROPIC_MODEL;
34
+ if (fromEnv)
35
+ return resolveValue(fromEnv, 'env', 'ANTHROPIC_MODEL', ctx.env);
36
+ if (sources === 'explicit')
37
+ return { kind: 'none' };
38
+ }
39
+ return settingsModel(ctx, cmd);
40
+ }
41
+ /**
42
+ * The command line of a process: /proc on Linux, which keeps argument boundaries, and `ps` on macOS,
43
+ * which has no such file. Null when it cannot be read.
44
+ */
45
+ export function readCommandLine(pid, platform) {
46
+ if (!Number.isSafeInteger(pid) || pid <= 1)
47
+ return null;
48
+ if (platform === 'linux') {
49
+ try {
50
+ const args = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0');
51
+ if (args.at(-1) === '')
52
+ args.pop();
53
+ return args.length ? { args, exact: true } : null;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ if (platform === 'darwin') {
60
+ const r = spawnSync('/bin/ps', ['-ww', '-o', 'args=', '-p', String(pid)], { encoding: 'utf8', timeout: 2000 });
61
+ const text = r.status === 0 ? r.stdout.trim() : '';
62
+ return text ? { args: text.split(/\s+/), exact: false } : null;
63
+ }
64
+ return null;
65
+ }
66
+ /** Every value given to an option, as --name value or --name=value, up to a "--" that ends the options. */
67
+ export function optionValues(cmd, name) {
68
+ const values = [];
69
+ for (let i = 0; i < cmd.args.length; i++) {
70
+ const a = cmd.args[i] ?? '';
71
+ if (a === '--' && cmd.exact)
72
+ break;
73
+ if (a === name) {
74
+ const value = cmd.args[i + 1];
75
+ if (value !== undefined)
76
+ values.push(value);
77
+ i++;
78
+ }
79
+ else if (a.startsWith(`${name}=`))
80
+ values.push(a.slice(name.length + 1));
81
+ }
82
+ return values;
83
+ }
84
+ /**
85
+ * The values an option may have been given. On an exact command line, the last one, which Claude Code
86
+ * uses. Without argument boundaries a prompt can hold the option's text too, so every distinct value is
87
+ * a candidate, and more than one means the option cannot be read.
88
+ */
89
+ export function optionCandidates(cmd, name) {
90
+ const values = optionValues(cmd, name);
91
+ if (cmd.exact)
92
+ return values.slice(-1);
93
+ return [...new Set(values)];
94
+ }
95
+ export const NO_BOUNDARIES = 'a command line read without argument boundaries cannot tell the option from prompt text';
96
+ /** A --setting-sources value: a comma-separated list of the settings files Claude Code may read. */
97
+ const SETTING_SOURCES = /^(?:user|project|local)(?:,(?:user|project|local))*$/;
98
+ /** Values that name a model: a Claude model identifier in any provider's form, or an alias. */
99
+ const LOOKS_LIKE_MODEL = new RegExp(`^(?:[a-z0-9._:@/-]*claude[a-z0-9._:@/-]*|${[...MODEL_ALIASES.map((a) => a.alias), ...RUNTIME_MODEL_VALUES].join('|')})(?:\\[1m\\])?$`, 'i');
100
+ export function modelArgument(cmd, env) {
101
+ const values = optionCandidates(cmd, '--model');
102
+ const value = values[0];
103
+ if (value === undefined)
104
+ return null;
105
+ // Without argument boundaries, a value that names no Claude model may be prompt text or a custom
106
+ // model identifier; either way a lower source would not decide, so it is reported instead.
107
+ if (values.length > 1 || (!cmd.exact && !LOOKS_LIKE_MODEL.test(value)))
108
+ return { kind: 'unresolved', value: values.join(' or '), source: 'claude-args', from: '--model', why: NO_BOUNDARIES };
109
+ return resolveValue(value, 'claude-args', '--model', env);
110
+ }
111
+ /**
112
+ * The model setting, from the settings Claude Code ranks highest
113
+ * (https://code.claude.com/docs/en/settings, "Settings precedence"): managed settings, then
114
+ * --settings, then the project's local and shared settings, then the user's.
115
+ */
116
+ function settingsModel(ctx, cmd) {
117
+ const configDir = defaultAccountDir(ctx.env, ctx.home);
118
+ // Managed: server-managed settings cached for this login, else the managed settings files.
119
+ const remote = remoteSettingsApply(ctx.env) ? readRemoteSettings(configDir) : null;
120
+ if (remote?.deliversPolicy && typeof remote.settings.model === 'string' && remote.settings.model)
121
+ return resolveValue(remote.settings.model, 'settings', remote.file, ctx.env);
122
+ if (managedFilesApply(remote)) {
123
+ const managedDir = safeManagedDir(ctx.env);
124
+ const files = managedDir ? readManagedFiles(managedDir) : null;
125
+ if (files && typeof files.merged.model === 'string' && files.merged.model)
126
+ return resolveValue(files.merged.model, 'settings', files.origins.model ?? managedDir ?? '', ctx.env);
127
+ }
128
+ // --settings: a file, or inline JSON.
129
+ const inlines = cmd ? optionCandidates(cmd, '--settings') : [];
130
+ if (inlines.length > 1)
131
+ return { kind: 'unresolved', value: inlines.join(' or '), source: 'settings', from: '--settings', why: NO_BOUNDARIES };
132
+ const inline = inlines[0];
133
+ if (inline !== undefined) {
134
+ const value = readSettingsArgument(inline);
135
+ if (value === undefined)
136
+ return { kind: 'unresolved', value: inline, source: 'settings', from: '--settings', why: 'noonsight could not read the --settings value' };
137
+ if (value !== null)
138
+ return resolveValue(value, 'settings', '--settings', ctx.env);
139
+ }
140
+ // --setting-sources narrows the files below to the ones it lists.
141
+ const listed = settingSources(cmd);
142
+ if (listed.kind === 'unresolved')
143
+ return { kind: 'unresolved', value: listed.value, source: 'settings', from: '--setting-sources', why: NO_BOUNDARIES };
144
+ const sources = listed.kind === 'listed' ? listed.sources : null;
145
+ const project = ctx.env.CLAUDE_PROJECT_DIR || ctx.cwd;
146
+ const files = [
147
+ ['local', project ? path.join(project, '.claude', 'settings.local.json') : null],
148
+ ['project', project ? path.join(project, '.claude', 'settings.json') : null],
149
+ ['user', path.join(configDir, 'settings.json')],
150
+ ];
151
+ for (const [source, file] of files) {
152
+ if (file === null || (sources !== null && !sources.has(source)))
153
+ continue;
154
+ const value = modelOf(readObject(file));
155
+ if (value !== null)
156
+ return resolveValue(value, 'settings', file, ctx.env);
157
+ }
158
+ return { kind: 'none' };
159
+ }
160
+ /**
161
+ * Claude Code fetches server-managed settings only when the session talks to Anthropic's API
162
+ * directly (https://code.claude.com/docs/en/managed-settings, "How Claude Code combines managed
163
+ * sources"); behind another provider or another API address it starts at the next managed source.
164
+ */
165
+ export function remoteSettingsApply(env) {
166
+ if (PROVIDER_VARS.some((v) => isSet(env[v])))
167
+ return false;
168
+ if (!env.ANTHROPIC_BASE_URL)
169
+ return true;
170
+ try {
171
+ return new URL(env.ANTHROPIC_BASE_URL).hostname === 'api.anthropic.com';
172
+ }
173
+ catch {
174
+ return false;
175
+ }
176
+ }
177
+ /** The model a --settings value sets: null when it sets none, undefined when it cannot be read. */
178
+ function readSettingsArgument(value) {
179
+ const parsed = settingsArgument(value);
180
+ return parsed === null ? undefined : modelOf(parsed);
181
+ }
182
+ /** The settings a --settings value gives, inline JSON or a file; null when they cannot be read. */
183
+ export function settingsArgument(value) {
184
+ if (!value.trimStart().startsWith('{'))
185
+ return readObject(value);
186
+ try {
187
+ const parsed = JSON.parse(value);
188
+ return isObject(parsed) ? parsed : null;
189
+ }
190
+ catch {
191
+ return null;
192
+ }
193
+ }
194
+ /** What --setting-sources lists on a command line; every source when the option is absent or the command line unknown. */
195
+ export function settingSources(cmd) {
196
+ const lists = cmd ? optionCandidates(cmd, '--setting-sources') : [];
197
+ if (lists.length > 1 || (cmd !== null && !cmd.exact && lists.some((l) => !SETTING_SOURCES.test(l))))
198
+ return { kind: 'unresolved', value: lists.join(' or ') };
199
+ const listed = lists[0];
200
+ return listed === undefined ? { kind: 'all' } : { kind: 'listed', sources: new Set(listed.split(',').map((s) => s.trim())) };
201
+ }
202
+ /**
203
+ * The model a value selects. An alias resolves through the environment variable that pins it, and
204
+ * otherwise, on the Anthropic API only, to the model the documentation names for it.
205
+ */
206
+ export function resolveValue(value, source, from, env) {
207
+ const r = resolveModelValue(value, env);
208
+ if (r.kind === 'unresolved')
209
+ return { kind: 'unresolved', value, source, from, why: r.why };
210
+ return { kind: 'found', model: r.model, source, from, ...(r.aliasFrom !== undefined ? { alias: value, aliasFrom: r.aliasFrom } : {}) };
211
+ }
212
+ /** What the decision log records about a model taken from the session's start. */
213
+ export function launchFields(launch) {
214
+ if (launch === null || launch.kind === 'none')
215
+ return {};
216
+ if (launch.kind === 'unresolved')
217
+ return { model_from: launch.from, model_unresolved: launch.value, unresolved_why: launch.why };
218
+ return {
219
+ model_from: launch.from,
220
+ ...(launch.alias !== undefined ? { model_alias: launch.alias, alias_from: launch.aliasFrom } : {}),
221
+ };
222
+ }
223
+ /** The model a model setting, an alias or an identifier, selects; see resolveValue. */
224
+ export function resolveModelValue(value, env) {
225
+ const bare = value.trim().replace(/\[1m\]$/i, '').toLowerCase();
226
+ if (RUNTIME_MODEL_VALUES.includes(bare))
227
+ return { kind: 'unresolved', why: 'Claude Code chooses that model while the session runs' };
228
+ const alias = MODEL_ALIASES.find((a) => a.alias === bare);
229
+ if (alias) {
230
+ const pinned = normalizeModel(env[alias.envVar]);
231
+ if (pinned && !MODEL_ALIASES.some((a) => a.alias === pinned))
232
+ return { kind: 'found', model: pinned, aliasFrom: alias.envVar };
233
+ const provider = otherProvider(env);
234
+ if (provider)
235
+ return { kind: 'unresolved', why: `the alias selects another model when ${provider} is set; set ${alias.envVar}` };
236
+ return { kind: 'found', model: alias.model, aliasFrom: 'built-in' };
237
+ }
238
+ const model = normalizeModel(value);
239
+ if (!model)
240
+ return { kind: 'unresolved', why: 'it names no model' };
241
+ return { kind: 'found', model };
242
+ }
243
+ /** The variable that moves Claude Code off the Anthropic API, or undefined when none is set. */
244
+ export function otherProvider(env) {
245
+ return PROVIDER_VARS.find((v) => isSet(env[v]));
246
+ }
247
+ export function isSet(value) {
248
+ return value !== undefined && !['', '0', 'false', 'no', 'off'].includes(value.trim().toLowerCase());
249
+ }
250
+ function modelOf(settings) {
251
+ return isObject(settings) && typeof settings.model === 'string' && settings.model !== '' ? settings.model : null;
252
+ }
253
+ export function readObject(file) {
254
+ try {
255
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
256
+ return isObject(value) ? value : null;
257
+ }
258
+ catch {
259
+ return null;
260
+ }
261
+ }
262
+ export function safeManagedDir(env) {
263
+ try {
264
+ return managedTarget(env).managedDir ?? null;
265
+ }
266
+ catch {
267
+ return null;
268
+ }
269
+ }
270
+ //# sourceMappingURL=launch.js.map