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,48 @@
1
+ // The hook pointer: a small shell script at a fixed path that Claude Code's settings call. It runs
2
+ // the installed copy of noonsight by absolute paths, so the hook does not depend on the PATH of
3
+ // whatever started Claude Code. Reinstalling or updating noonsight rewrites only this file; the
4
+ // settings entries that call it never change.
5
+ import fs from 'node:fs';
6
+ export function pointerScript(t) {
7
+ return [
8
+ '#!/bin/sh',
9
+ `# noonsight hook pointer, written by \`noonsight install\`.`,
10
+ '# Claude Code settings run this file; it runs the installed copy of noonsight.',
11
+ `# kind: ${t.kind}`,
12
+ `# version: ${t.version}`,
13
+ `node=${shellQuote(t.node)}`,
14
+ `cli=${shellQuote(t.cli)}`,
15
+ 'if [ -x "$node" ] && [ -f "$cli" ]; then',
16
+ ` exec "$node" "$cli" hook --install ${t.kind} "$@"`,
17
+ 'fi',
18
+ '# The installed copy is gone. A hook never holds the session, so exit quietly;',
19
+ '# `noonsight check` reports the missing copy.',
20
+ 'exit 0',
21
+ '',
22
+ ].join('\n');
23
+ }
24
+ /** The target a pointer file runs, or null when the file is missing or was not written by noonsight. */
25
+ export function readPointer(file) {
26
+ let text;
27
+ try {
28
+ text = fs.readFileSync(file, 'utf8');
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ const field = (re) => re.exec(text)?.[1];
34
+ const node = field(/^node=('(?:[^']|'\\'')*')$/m);
35
+ const cli = field(/^cli=('(?:[^']|'\\'')*')$/m);
36
+ const kind = field(/^# kind: (managed|account)$/m);
37
+ const version = field(/^# version: (\S+)$/m);
38
+ if (!node || !cli || !kind || !version)
39
+ return null;
40
+ return { node: shellUnquote(node), cli: shellUnquote(cli), kind: kind, version };
41
+ }
42
+ function shellQuote(s) {
43
+ return `'${s.replace(/'/g, `'\\''`)}'`;
44
+ }
45
+ function shellUnquote(s) {
46
+ return s.slice(1, -1).replace(/'\\''/g, "'");
47
+ }
48
+ //# sourceMappingURL=pointer.js.map
@@ -0,0 +1,271 @@
1
+ // The model a subagent will run on, decided before it starts, the way Claude Code decides it
2
+ // (https://code.claude.com/docs/en/sub-agents, "Choose a model" and "Built-in subagents"):
3
+ //
4
+ // 1. the model parameter of the agent call, an alias;
5
+ // 2. the model field of the subagent's definition, or of a built-in subagent;
6
+ // 3. the CLAUDE_CODE_SUBAGENT_MODEL environment variable;
7
+ // 4. the model of whoever starts it: the session, or the subagent that starts a nested one.
8
+ //
9
+ // A family alias (opus, sonnet, haiku, fable) selects the parent's own model when the parent is of
10
+ // that family. With CLAUDE_CODE_SUBAGENT_MODEL_FORCE set, definitions and the call's parameter are
11
+ // ignored. A fork always runs on its parent's model.
12
+ //
13
+ // The prediction is checked after the subagent starts: the result of the agent call names the model
14
+ // it started on (resolvedModel), and a difference is logged and shown.
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { normalizeModel } from '../../core/normalize.js';
18
+ import { isSet, otherProvider, resolveModelValue } from './launch.js';
19
+ /**
20
+ * The built-in subagents whose model does not simply follow the order above, from
21
+ * https://code.claude.com/docs/en/sub-agents, "Built-in subagents" (read 2026-11-15). A definition
22
+ * of the same name replaces a built-in, with its own model field.
23
+ */
24
+ const BUILT_IN_MODELS = {
25
+ 'statusline-setup': 'sonnet',
26
+ 'claude-code-guide': 'haiku',
27
+ };
28
+ /** Built-ins that run on their parent's model even when CLAUDE_CODE_SUBAGENT_MODEL is set. */
29
+ const PARENT_BUILT_INS = new Set(['Explore', 'Plan']);
30
+ /**
31
+ * The built-in web-fetch subagent, which the documentation does not list. Claude Code 2.1.326 gives it
32
+ * the model the haiku alias selects when it runs on the Anthropic API, and its parent's model on
33
+ * another provider, as its built-in definition reads.
34
+ */
35
+ const WEB_FETCH = 'web-fetch';
36
+ const FAMILIES = ['opus', 'sonnet', 'haiku', 'fable'];
37
+ export function predict(input) {
38
+ const { subagentType: type, requested, parent, env } = input;
39
+ const subagentModel = env.CLAUDE_CODE_SUBAGENT_MODEL?.trim() || null;
40
+ if (type === 'fork')
41
+ return fromParent(parent, 'fork');
42
+ if (isSet(env.CLAUDE_CODE_SUBAGENT_MODEL_FORCE)) {
43
+ if (subagentModel !== null)
44
+ return fromValue(subagentModel, parent, env, 'forced');
45
+ // Forced onto the session's model, except that Explore keeps its own rule.
46
+ if (type === 'Explore')
47
+ return explore(parent, env);
48
+ return fromParent(parent, 'forced');
49
+ }
50
+ if (requested !== null)
51
+ return fromValue(requested, parent, env, 'parameter');
52
+ const lookup = input.findDefinition(type);
53
+ if (lookup.kind === 'found') {
54
+ const { definition } = lookup;
55
+ if (definition.model !== null)
56
+ return { ...fromValue(definition.model, parent, env, 'definition'), definition: definition.file, definitionSource: definition.source };
57
+ }
58
+ else if (lookup.kind === 'unread') {
59
+ // A place that may define the subagent cannot be read, so a model it sets is not seen; the check
60
+ // after the subagent starts reports a difference.
61
+ const fallback = subagentModel !== null ? fromValue(subagentModel, parent, env, 'env') : fromParent(parent, 'parent');
62
+ return { ...fallback, definition: 'not-read', definitionWhy: lookup.why };
63
+ }
64
+ else if (!type.includes(':')) {
65
+ if (type === 'Explore')
66
+ return explore(parent, env);
67
+ if (PARENT_BUILT_INS.has(type))
68
+ return fromParent(parent, 'built-in');
69
+ if (type === WEB_FETCH)
70
+ return otherProvider(env) !== undefined ? fromParent(parent, 'built-in') : fromValue('haiku', parent, env, 'built-in');
71
+ const builtIn = BUILT_IN_MODELS[type];
72
+ if (builtIn !== undefined)
73
+ return fromValue(builtIn, parent, env, 'built-in');
74
+ }
75
+ if (subagentModel !== null)
76
+ return fromValue(subagentModel, parent, env, 'env');
77
+ return fromParent(parent, 'parent');
78
+ }
79
+ /**
80
+ * The built-in Explore subagent runs on its parent's model, except under a Fable parent: with a
81
+ * Claude subscription, an Anthropic Console account or a gateway reached through ANTHROPIC_BASE_URL
82
+ * it runs on the model the opus alias selects; on Amazon Bedrock, Google Cloud and Microsoft
83
+ * Foundry it stays on Fable.
84
+ */
85
+ function explore(parent, env) {
86
+ if (parent === null || familyOf(parent) !== 'fable' || otherProvider(env) !== undefined)
87
+ return fromParent(parent, 'built-in');
88
+ return fromValue('opus', parent, env, 'built-in');
89
+ }
90
+ function fromParent(parent, source) {
91
+ if (parent === null)
92
+ return { model: null, source, why: 'the model of the session or subagent that starts it is not known' };
93
+ return { model: parent, source };
94
+ }
95
+ /** The model a value names for a subagent: inherit, a family alias, another alias or a model identifier. */
96
+ function fromValue(value, parent, env, source) {
97
+ const bare = value.trim().toLowerCase();
98
+ if (bare === 'inherit')
99
+ return { ...fromParent(parent, source), value };
100
+ const family = FAMILIES.find((f) => f === bare.replace(/\[1m\]$/, ''));
101
+ if (family !== undefined && parent !== null && familyOf(parent) === family)
102
+ return { model: parent, source, value };
103
+ const r = resolveModelValue(value, env);
104
+ if (r.kind === 'unresolved')
105
+ return { model: null, source, value, why: `"${value}" cannot be pinned down: ${r.why}` };
106
+ return { model: r.model, source, value };
107
+ }
108
+ /** The family of a normalized model identifier, such as sonnet for claude-sonnet-5-5. */
109
+ export function familyOf(model) {
110
+ return FAMILIES.find((f) => new RegExp(`(?:^|-)${f}(?:-|$)`).test(model)) ?? null;
111
+ }
112
+ // ---------------------------------------------------------------------------------------------
113
+ // Transcripts. Claude Code writes each assistant message with the model that wrote it. A subagent's
114
+ // transcript sits next to the session's, at <session transcript dir>/<session id>/subagents/
115
+ // agent-<agent id>.jsonl, as the agent_transcript_path of the SubagentStop input shows
116
+ // (https://code.claude.com/docs/en/hooks, "SubagentStop input"). The documentation warns that a
117
+ // transcript can lag behind the conversation, so a transcript is read only when no record knows,
118
+ // except at a resume, when the conversation's earlier process has finished writing it.
119
+ //
120
+ // A compaction writes a system record with subtype compact_boundary, and the messages it kept are
121
+ // referred to there, not written again after it.
122
+ /** How much of a transcript is read at a time, from its end. */
123
+ const CHUNK_BYTES = 1024 * 1024;
124
+ /** How far back from its end a transcript is read at most, so the hook stays within its bound. */
125
+ const MAX_SCAN_BYTES = 64 * 1024 * 1024;
126
+ /** The model of the last assistant message in a transcript; for the session, its own messages only. */
127
+ export function transcriptModel(file, ownOnly) {
128
+ return lastResponse(file, ownOnly, false)?.model ?? null;
129
+ }
130
+ /**
131
+ * The conversation's last response since its last compaction, its own messages only: its model is
132
+ * the one Claude Code resumes a conversation on when nothing it was started with names one. Null when
133
+ * the conversation has no response since, or the transcript cannot be read.
134
+ */
135
+ export function conversationResponse(file) {
136
+ return lastResponse(file, true, true);
137
+ }
138
+ /** The model of conversationResponse. */
139
+ export function conversationModel(file) {
140
+ return conversationResponse(file)?.model ?? null;
141
+ }
142
+ function lastResponse(file, ownOnly, sinceCompaction) {
143
+ if (file === null)
144
+ return null;
145
+ let found = null;
146
+ try {
147
+ scanLinesBackward(file, (line) => {
148
+ const boundary = sinceCompaction && line.includes('"compact_boundary"');
149
+ if (!boundary && !line.includes('"assistant"'))
150
+ return false;
151
+ let r;
152
+ try {
153
+ r = JSON.parse(line);
154
+ }
155
+ catch {
156
+ // A torn line being written, or not a record.
157
+ return false;
158
+ }
159
+ if (ownOnly && r.isSidechain === true)
160
+ return false;
161
+ if (boundary && r.type === 'system' && r.subtype === 'compact_boundary')
162
+ return true;
163
+ if (r.type !== 'assistant')
164
+ return false;
165
+ const model = typeof r.message?.model === 'string' ? normalizeModel(r.message.model) : '';
166
+ if (!model || model === '<synthetic>')
167
+ return false;
168
+ const at = typeof r.timestamp === 'string' ? Date.parse(r.timestamp) : NaN;
169
+ found = { model, at: Number.isNaN(at) ? null : at };
170
+ return true;
171
+ });
172
+ }
173
+ catch {
174
+ return null;
175
+ }
176
+ return found;
177
+ }
178
+ /**
179
+ * The calls among `ids` that a transcript shows refused: their tool result is an error, as Claude Code
180
+ * writes it at once when a person rejects the call at its permission prompt, or a rule or a hook denies
181
+ * it. A call whose result is not an error, or not written yet, is not among them. The transcript is
182
+ * read from its end back to the calls themselves.
183
+ */
184
+ export function refusedCalls(file, ids) {
185
+ const refused = new Set();
186
+ const pending = new Set(ids);
187
+ if (file === null || pending.size === 0)
188
+ return refused;
189
+ const blocks = (line) => {
190
+ try {
191
+ const content = JSON.parse(line).message?.content;
192
+ return Array.isArray(content) ? content.filter((b) => typeof b === 'object' && b !== null) : [];
193
+ }
194
+ catch {
195
+ return [];
196
+ }
197
+ };
198
+ try {
199
+ scanLinesBackward(file, (line) => {
200
+ if (line.includes('"tool_result"'))
201
+ for (const b of blocks(line))
202
+ if (b.type === 'tool_result' && b.is_error === true && typeof b.tool_use_id === 'string' && pending.has(b.tool_use_id))
203
+ refused.add(b.tool_use_id);
204
+ if (line.includes('"tool_use"'))
205
+ for (const b of blocks(line))
206
+ if (b.type === 'tool_use' && typeof b.id === 'string')
207
+ pending.delete(b.id);
208
+ return pending.size === 0;
209
+ });
210
+ }
211
+ catch {
212
+ // An unreadable transcript shows nothing refused.
213
+ }
214
+ return refused;
215
+ }
216
+ /** Each line of a file, the last first, until `visit` returns true or MAX_SCAN_BYTES are read. */
217
+ function scanLinesBackward(file, visit) {
218
+ const fd = fs.openSync(file, 'r');
219
+ try {
220
+ let position = fs.fstatSync(fd).size;
221
+ const floor = Math.max(0, position - MAX_SCAN_BYTES);
222
+ // The start of the line the previous chunk ended in, which this chunk completes.
223
+ let carry = Buffer.alloc(0);
224
+ while (position > floor) {
225
+ const length = Math.min(CHUNK_BYTES, position - floor);
226
+ position -= length;
227
+ const chunk = Buffer.alloc(length);
228
+ fs.readSync(fd, chunk, 0, length, position);
229
+ const buffer = carry.length ? Buffer.concat([chunk, carry]) : chunk;
230
+ let end = buffer.length;
231
+ for (let i = end - 1; i >= 0; i--) {
232
+ if (buffer[i] !== 0x0a)
233
+ continue;
234
+ if (visit(buffer.toString('utf8', i + 1, end)))
235
+ return;
236
+ end = i;
237
+ }
238
+ carry = buffer.subarray(0, end);
239
+ }
240
+ // The file's first line; a line the scan's limit cut is not whole, so it is left out.
241
+ if (position === 0 && carry.length)
242
+ visit(carry.toString('utf8'));
243
+ }
244
+ finally {
245
+ fs.closeSync(fd);
246
+ }
247
+ }
248
+ /** Where a subagent's transcript is, given the session's transcript path from the hook input. */
249
+ export function subagentTranscript(sessionTranscript, sessionId, agentId) {
250
+ if (sessionTranscript === null || sessionId === null || !/^[A-Za-z0-9_-]+$/.test(agentId) || !/^[A-Za-z0-9_-]+$/.test(sessionId))
251
+ return null;
252
+ return path.join(path.dirname(sessionTranscript), sessionId, 'subagents', `agent-${agentId}.jsonl`);
253
+ }
254
+ /**
255
+ * The call that started a subagent, from the metadata Claude Code writes next to the subagent's
256
+ * transcript (agent-<agent id>.meta.json, its toolUseId), or null when there is none yet. Claude Code
257
+ * 2.1.330 writes it after the subagent's SubagentStart hooks have run, so only a later hook finds it.
258
+ */
259
+ export function subagentCall(sessionTranscript, sessionId, agentId) {
260
+ const transcript = subagentTranscript(sessionTranscript, sessionId, agentId);
261
+ if (transcript === null)
262
+ return null;
263
+ try {
264
+ const meta = JSON.parse(fs.readFileSync(transcript.replace(/\.jsonl$/, '.meta.json'), 'utf8'));
265
+ return typeof meta.toolUseId === 'string' && meta.toolUseId !== '' ? meta.toolUseId : null;
266
+ }
267
+ catch {
268
+ return null;
269
+ }
270
+ }
271
+ //# sourceMappingURL=predict.js.map
@@ -0,0 +1,88 @@
1
+ // Routing in Claude Code: what counts as a model the caller already chose, how a routing table's
2
+ // model is written for each target, and what the decision log records about a route.
3
+ //
4
+ // launcher noonsight run adds --model and --effort to the claude command line. A model is written
5
+ // as the table writes it, an alias or an identifier, since --model takes both.
6
+ // subagents the agent call hook sets the call's model and effort parameters. The model parameter
7
+ // takes an alias only (https://code.claude.com/docs/en/sub-agents, "Choose a model"),
8
+ // so an identifier is written as the alias that selects it, when one does.
9
+ import { normalizeModel } from '../../core/normalize.js';
10
+ import { ROUTE_ALIASES } from '../../core/types.js';
11
+ import { isSet, resolveModelValue } from './launch.js';
12
+ /** The variable that, when set, wins over the effort a command line or an agent call sets. */
13
+ export const EFFORT_ENV = 'CLAUDE_CODE_EFFORT_LEVEL';
14
+ /** How noonsight run writes a table's model for --model, and the model that selects. */
15
+ export function launcherTranslation(env) {
16
+ return (model) => {
17
+ const r = resolveModelValue(model, env);
18
+ if (r.kind === 'unresolved')
19
+ return { why: `"${model}" cannot be pinned down: ${r.why}` };
20
+ return { value: model, model: r.model };
21
+ };
22
+ }
23
+ /**
24
+ * How the agent call hook writes a table's model for the call's model parameter, and the model that
25
+ * selects. `select` predicts the subagent's model for a given parameter, as Claude Code decides it.
26
+ */
27
+ export function subagentTranslation(select) {
28
+ return (model) => {
29
+ if (ROUTE_ALIASES.includes(model)) {
30
+ const selected = select(model);
31
+ return selected !== null ? { value: model, model: selected } : { why: `noonsight cannot tell which model "${model}" selects for this subagent` };
32
+ }
33
+ const target = normalizeModel(model);
34
+ const alias = ROUTE_ALIASES.find((a) => select(a) === target);
35
+ return alias !== undefined
36
+ ? { value: alias, model: target }
37
+ : { why: `the agent tool takes a model alias only, and no alias selects ${target} for this subagent` };
38
+ };
39
+ }
40
+ /**
41
+ * The model a subagent call already has, from the prediction of its model without routing. A fork and
42
+ * CLAUDE_CODE_SUBAGENT_MODEL_FORCE fix the model whatever the call asks; a model parameter, a
43
+ * definition, a built-in subagent's own model and a definition noonsight cannot read are the caller's
44
+ * or the author's choice.
45
+ */
46
+ export function subagentHeld(prediction) {
47
+ switch (prediction.source) {
48
+ case 'fork':
49
+ return { reason: 'fork', explicit: false };
50
+ case 'forced':
51
+ return { reason: 'model-forced', explicit: false };
52
+ case 'parameter':
53
+ return { reason: 'explicit-model', explicit: true };
54
+ case 'definition':
55
+ return { reason: 'definition-model', explicit: true };
56
+ case 'built-in':
57
+ return { reason: 'built-in-model', explicit: true };
58
+ default:
59
+ return prediction.definition === 'not-read' ? { reason: 'definition-not-read', explicit: true } : null;
60
+ }
61
+ }
62
+ /** What the decision log records for a call routing never got to decide on, such as under a refused configuration. */
63
+ export function notRouted(reason) {
64
+ return { routing: 'off', routing_reason: reason };
65
+ }
66
+ /** What the decision log records about a route. */
67
+ export function routeFields(route, env) {
68
+ const fields = { routing: route.routing, routing_reason: route.reason };
69
+ if (route.routing === 'yielded' && route.env !== undefined)
70
+ fields.routing_env = route.env;
71
+ if (route.routing === 'inherit' && route.from !== undefined)
72
+ fields.route_from = route.from;
73
+ if (route.routing === 'routed') {
74
+ fields.route_model = route.model;
75
+ fields.route_value = route.value;
76
+ if (route.effort !== undefined)
77
+ fields.route_effort = route.effort;
78
+ if (route.effortKept)
79
+ fields.route_effort_kept = true;
80
+ fields.route_option = route.option;
81
+ if (route.effort !== undefined && isSet(env[EFFORT_ENV]))
82
+ fields.route_effort_overridden_by = EFFORT_ENV;
83
+ }
84
+ if ((route.routing === 'routed' || route.routing === 'inherit') && route.skipped.length > 0)
85
+ fields.route_skipped = route.skipped;
86
+ return fields;
87
+ }
88
+ //# sourceMappingURL=routing.js.map
@@ -0,0 +1,189 @@
1
+ // noonsight's entries in a Claude Code settings file. Pure functions over the parsed JSON: they add,
2
+ // repair or remove noonsight's own hook handlers and never change anything else in the file.
3
+ //
4
+ // noonsight recognizes its handlers by the program they run: a file named noonsight-hook (the hook
5
+ // pointer), wherever it lives. Every other handler, matcher group and key belongs to someone else.
6
+ export const POINTER_NAME = 'noonsight-hook';
7
+ /**
8
+ * The names of the tool that starts a subagent. Claude Code calls it Agent; earlier versions called
9
+ * it Task, and both names are valid (https://code.claude.com/docs/en/sub-agents).
10
+ */
11
+ export const AGENT_TOOLS = ['Agent', 'Task'];
12
+ /**
13
+ * The tools that edit a file, whose input names it in file_path. Claude Code 2.1.326 offers these two;
14
+ * NotebookEdit edits notebooks, which are not code files to the code-edit trigger.
15
+ */
16
+ export const EDIT_TOOLS = ['Edit', 'Write'];
17
+ /**
18
+ * The handlers noonsight installs, one matcher group each: the Claude Code event, the argument the hook
19
+ * command receives, and for a tool event the tools its matcher names; an entry without tools has no
20
+ * matcher and runs on every occurrence.
21
+ * - The agent tool entries run noonsight only for the agent tool, under either name.
22
+ * - SubagentStart matches on the subagent's type, and runs for every type.
23
+ * - The file edit entry runs after a successful Edit or Write, for the code-edit trigger.
24
+ * The hook checks the tool name again itself, so a widened matcher reaches no other tool.
25
+ */
26
+ export const HOOK_HANDLERS = [
27
+ { event: 'SessionStart', arg: 'session-start', tools: undefined },
28
+ { event: 'PostModelSwitch', arg: 'model-switch', tools: undefined },
29
+ { event: 'PreToolUse', arg: 'agent-call', tools: AGENT_TOOLS },
30
+ { event: 'SubagentStart', arg: 'subagent-start', tools: undefined },
31
+ { event: 'PostToolUse', arg: 'agent-result', tools: AGENT_TOOLS },
32
+ { event: 'PostToolUse', arg: 'file-edit', tools: EDIT_TOOLS },
33
+ { event: 'PermissionRequest', arg: 'agent-held', tools: AGENT_TOOLS },
34
+ ];
35
+ /** The matcher of an entry: its tools, or none. */
36
+ export function matcherOf(spec) {
37
+ return spec.tools?.join('|');
38
+ }
39
+ /** The Claude Code events noonsight handles, each once. */
40
+ export const HOOK_EVENTS = [...new Set(HOOK_HANDLERS.map((h) => h.event))];
41
+ /**
42
+ * Seconds before Claude Code cancels the hook. The hook itself takes a fraction of a second; the
43
+ * limit only bounds a machine that has stopped responding, far below Claude Code's default of 600.
44
+ */
45
+ export const HOOK_TIMEOUT_SECONDS = 10;
46
+ /**
47
+ * The handler for one entry. It uses exec form (command plus args): no shell parses the path,
48
+ * so a directory such as "Application Support" needs no quoting.
49
+ */
50
+ export function handlerFor(pointer, spec) {
51
+ return { type: 'command', command: pointer, args: [spec.arg], timeout: HOOK_TIMEOUT_SECONDS };
52
+ }
53
+ /** A settings file whose shape noonsight will not edit; the message names where the shape is wrong. */
54
+ export class SettingsShapeError extends Error {
55
+ constructor(message) {
56
+ super(message);
57
+ this.name = 'SettingsShapeError';
58
+ }
59
+ }
60
+ export function isObject(value) {
61
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
62
+ }
63
+ export function isNoonsightHandler(handler) {
64
+ if (!isObject(handler) || typeof handler.command !== 'string')
65
+ return false;
66
+ const base = handler.command.split(/[\\/]/).pop();
67
+ return base === POINTER_NAME;
68
+ }
69
+ /** Every noonsight handler in the file, in order. Parts of the file with an unexpected shape are skipped. */
70
+ export function findNoonsightHandlers(settings) {
71
+ const found = [];
72
+ if (!isObject(settings) || !isObject(settings.hooks))
73
+ return found;
74
+ for (const [event, groups] of Object.entries(settings.hooks)) {
75
+ if (!Array.isArray(groups))
76
+ continue;
77
+ for (const group of groups) {
78
+ if (!isObject(group) || !Array.isArray(group.hooks))
79
+ continue;
80
+ for (const handler of group.hooks)
81
+ if (isNoonsightHandler(handler))
82
+ found.push({ event, matcher: group.matcher, handler: handler });
83
+ }
84
+ }
85
+ return found;
86
+ }
87
+ /** The matcher group noonsight adds for one entry. */
88
+ export function groupFor(pointer, spec) {
89
+ const matcher = matcherOf(spec);
90
+ return { ...(matcher !== undefined ? { matcher } : {}), hooks: [handlerFor(pointer, spec)] };
91
+ }
92
+ /** The found handlers that are exactly the entry for a spec: its event, matcher, and handler for this pointer. */
93
+ export function handlersFor(found, spec, pointer) {
94
+ return found.filter((f) => f.event === spec.event && f.matcher === matcherOf(spec) && sameHandler(f.handler, handlerFor(pointer, spec)));
95
+ }
96
+ /**
97
+ * The settings with exactly one noonsight handler per entry of HOOK_HANDLERS, each in its own matcher
98
+ * group with the entry's matcher, pointing at the given pointer. Running it again on its own result
99
+ * changes nothing.
100
+ */
101
+ export function withNoonsightHooks(settings, pointer) {
102
+ const base = checkShape(settings);
103
+ const found = findNoonsightHandlers(base);
104
+ const current = found.length === HOOK_HANDLERS.length && HOOK_HANDLERS.every((spec) => handlersFor(found, spec, pointer).length === 1);
105
+ if (current)
106
+ return { settings: base, changed: false };
107
+ const next = withoutNoonsightHooks(base).settings;
108
+ const hooks = isObject(next.hooks) ? next.hooks : (next.hooks = {});
109
+ for (const spec of HOOK_HANDLERS) {
110
+ const groups = Array.isArray(hooks[spec.event]) ? hooks[spec.event] : (hooks[spec.event] = []);
111
+ groups.push(groupFor(pointer, spec));
112
+ }
113
+ return { settings: next, changed: true };
114
+ }
115
+ /**
116
+ * The settings with every noonsight handler removed. A matcher group, an event or the hooks object is
117
+ * removed only when removing noonsight's handlers is what left it empty.
118
+ */
119
+ export function withoutNoonsightHooks(settings) {
120
+ const next = checkShape(settings);
121
+ if (!isObject(next.hooks))
122
+ return { settings: next, changed: false };
123
+ let changed = false;
124
+ for (const [event, groups] of Object.entries(next.hooks)) {
125
+ if (!Array.isArray(groups))
126
+ continue;
127
+ const kept = [];
128
+ let eventChanged = false;
129
+ for (const group of groups) {
130
+ if (!isObject(group) || !Array.isArray(group.hooks)) {
131
+ kept.push(group);
132
+ continue;
133
+ }
134
+ const handlers = group.hooks.filter((h) => !isNoonsightHandler(h));
135
+ if (handlers.length === group.hooks.length) {
136
+ kept.push(group);
137
+ continue;
138
+ }
139
+ eventChanged = true;
140
+ if (handlers.length > 0)
141
+ kept.push({ ...group, hooks: handlers });
142
+ }
143
+ if (!eventChanged)
144
+ continue;
145
+ changed = true;
146
+ if (kept.length > 0)
147
+ next.hooks[event] = kept;
148
+ else
149
+ delete next.hooks[event];
150
+ }
151
+ if (changed && Object.keys(next.hooks).length === 0)
152
+ delete next.hooks;
153
+ return { settings: next, changed };
154
+ }
155
+ /** A deep copy of the settings, after checking the parts noonsight edits have the documented shape. */
156
+ function checkShape(settings) {
157
+ if (!isObject(settings))
158
+ throw new SettingsShapeError('the file does not hold a JSON object');
159
+ const copy = structuredClone(settings);
160
+ if (copy.hooks === undefined)
161
+ return copy;
162
+ if (!isObject(copy.hooks))
163
+ throw new SettingsShapeError('"hooks" is not an object');
164
+ for (const event of HOOK_EVENTS) {
165
+ const groups = copy.hooks[event];
166
+ if (groups === undefined)
167
+ continue;
168
+ if (!Array.isArray(groups))
169
+ throw new SettingsShapeError(`"hooks.${event}" is not a list`);
170
+ groups.forEach((group, i) => {
171
+ if (!isObject(group) || !Array.isArray(group.hooks))
172
+ throw new SettingsShapeError(`"hooks.${event}[${i}]" is not a matcher group with a "hooks" list`);
173
+ });
174
+ }
175
+ return copy;
176
+ }
177
+ function sameHandler(a, b) {
178
+ return JSON.stringify(sortKeys(a)) === JSON.stringify(sortKeys(b));
179
+ }
180
+ function sortKeys(value) {
181
+ if (Array.isArray(value))
182
+ return value.map(sortKeys);
183
+ if (!isObject(value))
184
+ return value;
185
+ return Object.fromEntries(Object.keys(value)
186
+ .sort()
187
+ .map((k) => [k, sortKeys(value[k])]));
188
+ }
189
+ //# sourceMappingURL=settings.js.map