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,666 @@
1
+ // The Claude Code hook adapter for subagents: PreToolUse, PermissionRequest and PostToolUse on the
2
+ // agent tool, and SubagentStart.
3
+ //
4
+ // PreToolUse predicts the model the subagent will run on (predict.ts, definitions.ts) and resolves
5
+ // its rules for the place "subagent". It records them under the call's tool_use_id, and
6
+ // adds the call to its session's pool of calls whose subagent has not started. It returns
7
+ // the call changed, with the permission decision the configuration asks for, only when
8
+ // routing sets its model or effort; any other call gets no output that touches it, so the
9
+ // auto mode classifier's review of the response the call came in still holds. With
10
+ // classifier.mode on, a task its matchers did not place may wait for the classifier
11
+ // (classifier.ts), up to classifier.timeout_ms.
12
+ // PermissionRequest marks held the open call a permission prompt holds, so it stays open until the
13
+ // person answers; it never answers the request itself.
14
+ // SubagentStart gives the subagent the rules of the call that started it, as additionalContext. Its
15
+ // input names the subagent and its type (a teammate's name, for a teammate) but not the
16
+ // call, so it takes the one open call of that type in the session's pool, or the call
17
+ // whose result already named this subagent, leaving out calls the transcript shows
18
+ // refused. When several calls of the type are open, it waits briefly for a result to name
19
+ // it; failing that, the subagent gets only what every one of those calls would give, since
20
+ // the subagents of one response's calls start in no fixed order, and when that is nothing
21
+ // a later hook inside the subagent gives it its own call's rules (lateRules).
22
+ // PostToolUse compares the prediction with the model the subagent started on (resolvedModel in the
23
+ // tool's response), logs match or MISMATCH, and warns on a mismatch. It records the
24
+ // subagent's model under its agent id, for the calls that subagent makes in turn, and
25
+ // which call started that subagent, for a start not seen yet.
26
+ //
27
+ // Like the session hooks, none ever blocks a call: an undeclared or unknown model only warns.
28
+ import { createHash } from 'node:crypto';
29
+ import fs from 'node:fs';
30
+ import { normalizeModel } from '../../core/normalize.js';
31
+ import { resolve, scopeChangesRules } from '../../core/resolve.js';
32
+ import { route, routeReadsScope, routingGate } from '../../core/route.js';
33
+ import { taskScope, taskText } from '../../core/scope.js';
34
+ import { agentCallFile, agentFile, agentLinkFile, agentPendingFile, agentStartFile, changePool, pause, poolFile, readAgentCall, readAgentLink, readAgentModel, readAgentPending, readAgentStart, readPool, removeRecord, writeRecord, } from '../../state/agents.js';
35
+ import { readState, sessionFile } from '../../state/sessions.js';
36
+ import { classifiedScope } from './classifier.js';
37
+ import { definitionFinder } from './definitions.js';
38
+ import { launchModel, readCommandLine } from './launch.js';
39
+ import { defaultAccountDir } from './locations.js';
40
+ import { predict, refusedCalls, subagentCall, subagentTranscript, transcriptModel } from './predict.js';
41
+ import { notRouted, routeFields, subagentHeld, subagentTranslation } from './routing.js';
42
+ export function agentCall(input, config, ctx) {
43
+ const toolInput = input.tool_input;
44
+ const callFile = agentCallFile(ctx.state, str(input.tool_use_id));
45
+ if (typeof toolInput !== 'object' || toolInput === null || Array.isArray(toolInput))
46
+ return {
47
+ record: { status: 'error', error: 'the call has no tool_input', ...notRouted('error'), delivered: 'nothing', warned: false },
48
+ messages: [],
49
+ specific: null,
50
+ };
51
+ const ti = toolInput;
52
+ const subagentType = str(ti.subagent_type) ?? 'general-purpose';
53
+ const requested = str(ti.model);
54
+ const base = { subagent_type: subagentType, requested_model: requested, ...(str(ti.effort) !== null ? { requested_effort: str(ti.effort) } : {}) };
55
+ // With nothing to deliver and nothing to route, the call is left alone without reading anything.
56
+ const gate = routingGate(config, 'subagents', ctx.env);
57
+ if (config.subagents.delivery === 'off' && gate !== null)
58
+ return { record: { ...base, ...routeFields(gate, ctx.env), delivered: 'off', warned: false }, messages: [], specific: null };
59
+ const parent = parentModel(input, ctx);
60
+ const projectDir = ctx.env.CLAUDE_PROJECT_DIR || str(input.cwd);
61
+ const findDefinition = definitionFinder({
62
+ projectDir,
63
+ configDir: defaultAccountDir(ctx.env, ctx.home),
64
+ env: ctx.env,
65
+ commandLine: () => readCommandLine(ctx.parentPid, process.platform),
66
+ });
67
+ const predictWith = (model) => predict({ subagentType, requested: model, parent: parent.model, env: ctx.env, findDefinition });
68
+ const prompt = typeof ti.prompt === 'string' ? ti.prompt : null;
69
+ // The route is decided from the model the call would get as it stands, and the rules for the model it
70
+ // gets once routed.
71
+ const asCalled = predictWith(requested);
72
+ const held = subagentHeld(asCalled);
73
+ // The subagent's own task decides its scope; the session's scope does not carry over.
74
+ const task = taskText(str(ti.description), prompt);
75
+ const classified = classifiedScope(config, {
76
+ chosen: taskScope(config, task.text),
77
+ text: task.text,
78
+ matters: () => routeReadsScope(config, { target: 'subagents', env: ctx.env, held }) ||
79
+ (config.subagents.delivery !== 'off' && scopeChangesRules(config, asCalled.model, 'subagent')),
80
+ env: ctx.env,
81
+ });
82
+ const scope = classified.scope;
83
+ const unplaced = classified.failure !== null
84
+ ? [`noonsight: the classifier could not place the task of subagent ${subagentType} (${classified.failure}), so it has no scope.`]
85
+ : [];
86
+ const lookup = findDefinition(subagentType);
87
+ const definitionEffort = lookup.kind === 'found' ? lookup.definition.effort : null;
88
+ const routed = route(config, {
89
+ target: 'subagents',
90
+ scope: scope.scope,
91
+ env: ctx.env,
92
+ held,
93
+ explicitEffort: str(ti.effort) !== null || definitionEffort !== null,
94
+ translate: subagentTranslation((alias) => predictWith(alias).model),
95
+ });
96
+ const changes = routed.routing === 'routed' ? { model: routed.value, ...(routed.effort !== undefined ? { effort: routed.effort } : {}) } : {};
97
+ const routing = routeFields(routed, ctx.env);
98
+ if (config.subagents.delivery === 'off') {
99
+ const specific = Object.keys(changes).length > 0 ? changed(config, { ...ti, ...changes }, changes) : null;
100
+ return {
101
+ record: {
102
+ ...base,
103
+ ...choiceFields(scope),
104
+ ...classified.fields,
105
+ ...routing,
106
+ delivered: 'off',
107
+ ...(specific !== null ? { permission: config.subagents.permission } : {}),
108
+ warned: unplaced.length > 0,
109
+ },
110
+ messages: unplaced,
111
+ specific,
112
+ };
113
+ }
114
+ const prediction = routed.routing === 'routed' ? predictWith(routed.value) : asCalled;
115
+ const decision = resolve(config, { model: prediction.model, scope: scope.scope, place: 'subagent' });
116
+ // The rules are handed to the subagent when it starts, not added to the task text: a changed call
117
+ // costs the other calls of the same response their auto mode review.
118
+ const planned = decision.status !== 'matched' ? 'nothing' : prompt !== null && prompt.includes(decision.text) ? 'already-delivered' : 'at-start';
119
+ const specific = Object.keys(changes).length > 0 ? changed(config, { ...ti, ...changes }, changes) : null;
120
+ const call = {
121
+ session_id: str(input.session_id),
122
+ subagent_type: subagentType,
123
+ predicted: decision.model,
124
+ status: decision.status,
125
+ sha256: decision.status === 'matched' ? decision.sha256 : null,
126
+ delivered: planned,
127
+ ...(planned === 'at-start' && decision.status === 'matched' ? { text: decision.text, rules: decision.rules, scope: decision.scope } : {}),
128
+ routing: routed.routing,
129
+ routing_reason: routed.reason,
130
+ at: ctx.now.toISOString(),
131
+ };
132
+ const toolUseId = str(input.tool_use_id);
133
+ const sessionId = str(input.session_id);
134
+ // A call with no rules is recorded too, so that its subagent's start never takes another call's rules.
135
+ let failure = null;
136
+ try {
137
+ writeRecord(callFile, call);
138
+ if (callFile !== null && toolUseId !== null && sessionId !== null)
139
+ changePool(ctx.state, sessionId, (pool) => ({
140
+ pool: { open: [...pool.open, openCall(toolUseId, subagentType, call.at, specific !== null ? { ...ti, ...changes } : ti, str(input.agent_id))], groups: pool.groups },
141
+ value: undefined,
142
+ }));
143
+ }
144
+ catch (e) {
145
+ failure = e instanceof Error ? e.message : String(e);
146
+ }
147
+ // Without the record, the subagent's start finds no call, so it gets no rules, and its result is not checked.
148
+ const delivered = failure !== null && planned === 'at-start' ? 'nothing' : planned;
149
+ const messages = [
150
+ ...unplaced,
151
+ ...undeclaredMessages(decision, prediction, subagentType, ctx.file),
152
+ ...(failure !== null && planned === 'at-start' ? [`noonsight: noonsight could not record the call of subagent ${subagentType} (${failure}), so it gets no rules.`] : []),
153
+ ];
154
+ return {
155
+ record: {
156
+ ...base,
157
+ parent_model: parent.model,
158
+ parent_source: parent.source,
159
+ ...decisionFields(decision),
160
+ ...choiceFields(scope),
161
+ ...classified.fields,
162
+ ...(task.cut ? { task_text_cut: true } : {}),
163
+ model_source: prediction.source,
164
+ ...(prediction.value !== undefined ? { model_value: prediction.value } : {}),
165
+ ...(prediction.definition !== undefined ? { definition: prediction.definition } : {}),
166
+ ...(prediction.definitionSource !== undefined ? { definition_source: prediction.definitionSource } : {}),
167
+ ...(prediction.definitionWhy !== undefined ? { definition_why: prediction.definitionWhy } : {}),
168
+ ...(prediction.why !== undefined ? { unresolved_why: prediction.why } : {}),
169
+ ...routing,
170
+ delivered,
171
+ ...(failure !== null ? { error: failure } : {}),
172
+ ...(specific !== null ? { permission: config.subagents.permission } : {}),
173
+ warned: messages.length > 0,
174
+ },
175
+ messages,
176
+ specific,
177
+ };
178
+ }
179
+ /**
180
+ * A call as its session's pool keeps it. A call that gives a name, and is neither a fork nor isolated,
181
+ * starts an agent team teammate when teams are on, whose start names it by that name instead of its type
182
+ * (seen on Claude Code 2.1.330). The hash of its input, as Claude Code runs it, finds it again when a
183
+ * permission prompt holds it, since a permission request names the input but not the call.
184
+ */
185
+ function openCall(id, type, at, toolInput, by) {
186
+ const name = str(toolInput.name);
187
+ const teammate = name !== null && type !== 'fork' && toolInput.isolation === undefined;
188
+ return { id, type, at, ...(teammate ? { name } : {}), input: inputHash(toolInput), ...(by !== null ? { by } : {}) };
189
+ }
190
+ /** A hash of a tool input that does not depend on the order of its keys. */
191
+ function inputHash(value) {
192
+ const canonical = (v) => Array.isArray(v)
193
+ ? v.map(canonical)
194
+ : typeof v === 'object' && v !== null
195
+ ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canonical(v[k])]))
196
+ : v;
197
+ return createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex').slice(0, 32);
198
+ }
199
+ /**
200
+ * PermissionRequest on the agent tool: a permission prompt is about to hold a call, for as long as the
201
+ * person takes to answer. The call is marked held, so it stays open past the windows that leave out a
202
+ * call whose subagent did not start in time. The request carries the call's input but not its id, so
203
+ * the call is the newest open one with the same input from the same caller. It never answers the
204
+ * request: the person, or another hook, does.
205
+ */
206
+ export function agentHeld(input, config, ctx) {
207
+ const sessionId = str(input.session_id);
208
+ const toolInput = input.tool_input;
209
+ if (sessionId === null || typeof toolInput !== 'object' || toolInput === null || Array.isArray(toolInput) || config.subagents.delivery === 'off')
210
+ return null;
211
+ const hash = inputHash(toolInput);
212
+ const by = str(input.agent_id) ?? undefined;
213
+ const now = ctx.now.toISOString();
214
+ const held = changePool(ctx.state, sessionId, (found) => {
215
+ const pool = current(found, ctx.now.getTime());
216
+ const match = [...pool.open].reverse().find((c) => c.input === hash && c.by === by && c.held === undefined);
217
+ if (match === undefined)
218
+ return { pool: null, value: null };
219
+ return { pool: { open: pool.open.map((c) => (c.id === match.id ? { ...c, held: now } : c)), groups: pool.groups }, value: match.id };
220
+ });
221
+ // Nothing noonsight saw: delivery was off for the call, or its record could not be written.
222
+ if (held === null)
223
+ return null;
224
+ return { record: { subagent_type: str(toolInput.subagent_type) ?? 'general-purpose', call_id: held, held: true, warned: false }, messages: [], specific: null };
225
+ }
226
+ /** The hookSpecificOutput for a call routing changed, with the permission decision the configuration asks for. */
227
+ function changed(config, updatedInput, routed) {
228
+ const permission = config.subagents.permission;
229
+ const set = Object.entries(routed).map(([k, v]) => `${k} ${String(v)}`);
230
+ return {
231
+ hookEventName: 'PreToolUse',
232
+ ...(permission !== 'passthrough'
233
+ ? { permissionDecision: permission, permissionDecisionReason: `noonsight set the subagent's ${set.join(' and ')} from its task scope` }
234
+ : {}),
235
+ updatedInput,
236
+ };
237
+ }
238
+ /**
239
+ * How long an open call can wait for its subagent to start. A subagent starts within seconds of its
240
+ * call's hook, while a call denied after its hook ran never starts and no hook says so; until it is
241
+ * left out, a later start of its type cannot tell its own call from it.
242
+ */
243
+ const OPEN_FOR_MS = 2 * 60 * 1000;
244
+ /**
245
+ * How long before the newest open call of its type a call can have been made and still be its sibling.
246
+ * The calls of one response reach their hooks within moments of each other, so an open call made
247
+ * earlier than this came from an earlier response and was denied after its hook ran.
248
+ */
249
+ const SIBLING_MS = 5000;
250
+ /**
251
+ * How long a call a permission prompt holds stays open. The person may answer the prompt long after the
252
+ * call was made; a call they reject is left out sooner, once the transcript shows it refused.
253
+ */
254
+ const HELD_FOR_MS = 24 * 60 * 60 * 1000;
255
+ /** How long a start that several open calls could own waits for a result to name it. */
256
+ const LINK_WAIT_MS = 2000;
257
+ const LINK_POLL_MS = 25;
258
+ /**
259
+ * SubagentStart: the rules for the subagent, from the call that started it. A resumed subagent gets
260
+ * the rules of its first start again; Claude Code adds them only when its context no longer holds them.
261
+ */
262
+ export function subagentStart(input, config, ctx) {
263
+ const agentId = str(input.agent_id);
264
+ const type = str(input.agent_type);
265
+ const sessionId = str(input.session_id);
266
+ const startFile = agentStartFile(ctx.state, agentId);
267
+ if (agentId === null || type === null || sessionId === null || startFile === null || config.subagents.delivery === 'off')
268
+ return null;
269
+ const earlier = readAgentStart(startFile);
270
+ if (earlier !== null)
271
+ return {
272
+ record: { agent_type: type, start_match: 'resumed', delivered: earlier.text !== null ? 'already-delivered' : 'nothing', warned: false },
273
+ messages: [],
274
+ specific: earlier.text !== null ? startContext(earlier.text) : null,
275
+ };
276
+ const now = ctx.now.getTime();
277
+ const linkFile = agentLinkFile(ctx.state, agentId);
278
+ const transcript = str(input.transcript_path);
279
+ const refused = refusedAmong(current(readPool(poolFile(ctx.state, sessionId)), now), type, transcript, sessionId);
280
+ const pendingFile = agentPendingFile(ctx.state, agentId);
281
+ // Decides under the pool's lock, and records the start there too, so that a result of the same call,
282
+ // running at the same time, sees either the start or nothing of it.
283
+ const decide = (final) => changePool(ctx.state, sessionId, (found) => {
284
+ const read = current(found, now);
285
+ const pool = refused.size > 0 ? settled({ open: read.open.filter((c) => !refused.has(c.id)), groups: read.groups }) : read;
286
+ const link = readAgentLink(linkFile);
287
+ let taken;
288
+ const candidates = pool.open.filter((c) => startsAs(c, type));
289
+ let next = pool;
290
+ if (link !== null) {
291
+ taken = { match: 'result', calls: [link.call] };
292
+ next = without(pool, link.call);
293
+ }
294
+ else if (candidates.length === 0)
295
+ taken = null;
296
+ else if (candidates.length === 1) {
297
+ const only = candidates[0]?.id;
298
+ taken = { match: 'single', calls: [only] };
299
+ next = without(pool, only);
300
+ }
301
+ else if (!final)
302
+ taken = 'wait';
303
+ else {
304
+ taken = { match: 'shared', calls: candidates.map((c) => c.id) };
305
+ next = withShared(pool, taken.calls);
306
+ }
307
+ // Nothing taken: the pool stays as recorded, but for refused calls; calls too old to start are left out when it is read.
308
+ if (taken === null || taken === 'wait')
309
+ return { pool: pool !== read ? pool : null, value: taken };
310
+ const given = startText(config, taken, ctx.state);
311
+ writeRecord(startFile, {
312
+ session_id: sessionId,
313
+ subagent_type: type,
314
+ match: taken.match,
315
+ calls: taken.calls,
316
+ text: given.text,
317
+ at: ctx.now.toISOString(),
318
+ });
319
+ // The result of a call that named this subagent has already been checked.
320
+ if (link !== null) {
321
+ removeRecord(agentCallFile(ctx.state, link.call));
322
+ removeRecord(linkFile);
323
+ }
324
+ // A later hook inside the subagent can still find its own call, and give it that call's rules.
325
+ if (given.fields.reason === 'calls-differ')
326
+ writeRecord(pendingFile, { session_id: sessionId, calls: taken.calls, at: ctx.now.toISOString() });
327
+ return { pool: next, value: { taken, given } };
328
+ });
329
+ for (const id of refused)
330
+ removeRecord(agentCallFile(ctx.state, id));
331
+ let decided = decide(false);
332
+ for (const until = Date.now() + LINK_WAIT_MS; decided === 'wait' && Date.now() < until;) {
333
+ pause(LINK_POLL_MS);
334
+ decided = decide(false);
335
+ }
336
+ if (decided === 'wait')
337
+ decided = decide(true);
338
+ // No call of this type is open: a subagent that did not start through the agent tool, such as a
339
+ // workflow's agent, or one whose call noonsight did not see.
340
+ if (decided === null || decided === 'wait')
341
+ return null;
342
+ const { taken, given } = decided;
343
+ return {
344
+ record: {
345
+ agent_type: type,
346
+ start_match: taken.match,
347
+ ...(taken.match === 'shared' ? { calls: taken.calls } : { call_id: taken.calls[0] ?? null }),
348
+ ...given.fields,
349
+ ...(refused.size > 0 ? { refused: [...refused] } : {}),
350
+ delivered: given.text !== null ? 'rules' : given.delivered,
351
+ warned: false,
352
+ },
353
+ messages: [],
354
+ specific: given.text !== null ? startContext(given.text) : null,
355
+ };
356
+ }
357
+ /** Whether a subagent that starts as `type` may come from the call: by the call's type, or by the name a teammate starts under. */
358
+ function startsAs(c, type) {
359
+ return c.type === type || c.name === type;
360
+ }
361
+ /**
362
+ * The open calls a start could come from that the transcripts show refused, such as one rejected at its
363
+ * permission prompt. Read only when a start has to choose: several calls of its type are open, or a
364
+ * permission prompt held one of them.
365
+ */
366
+ function refusedAmong(pool, type, transcript, sessionId) {
367
+ const candidates = pool.open.filter((c) => startsAs(c, type));
368
+ if (candidates.length < 2 && !candidates.some((c) => c.held !== undefined))
369
+ return new Set();
370
+ const refused = new Set();
371
+ const byCaller = new Map();
372
+ for (const c of candidates)
373
+ byCaller.set(c.by, [...(byCaller.get(c.by) ?? []), c.id]);
374
+ for (const [by, ids] of byCaller) {
375
+ const file = by === undefined ? transcript : subagentTranscript(transcript, sessionId, by);
376
+ for (const id of refusedCalls(file, ids))
377
+ refused.add(id);
378
+ }
379
+ return refused;
380
+ }
381
+ /**
382
+ * A later hook inside a subagent whose start could not tell its call from others that need other rules:
383
+ * by now Claude Code has written the subagent's metadata, which names its call, so the subagent gets that
384
+ * call's rules, late, through this hook's context. Null when the subagent has nothing pending, or its
385
+ * call cannot be told yet.
386
+ */
387
+ export function lateRules(input, ctx) {
388
+ const agentId = str(input.agent_id);
389
+ const pendingFile = agentPendingFile(ctx.state, agentId);
390
+ if (agentId === null || pendingFile === null || !fs.existsSync(pendingFile))
391
+ return null;
392
+ const pending = readAgentPending(pendingFile);
393
+ const sessionId = str(input.session_id);
394
+ if (pending === null || sessionId !== pending.session_id)
395
+ return null;
396
+ const callId = subagentCall(str(input.transcript_path), sessionId, agentId);
397
+ if (callId === null)
398
+ return null;
399
+ removeRecord(pendingFile);
400
+ // A metadata file that names another call than those the start chose from gives nothing.
401
+ if (!pending.calls.includes(callId))
402
+ return null;
403
+ const call = readAgentCall(agentCallFile(ctx.state, callId));
404
+ if (call === null || call.delivered !== 'at-start' || call.text === undefined)
405
+ return null;
406
+ const startFile = agentStartFile(ctx.state, agentId);
407
+ const start = readAgentStart(startFile);
408
+ try {
409
+ if (start !== null)
410
+ writeRecord(startFile, { ...start, calls: [callId], text: call.text });
411
+ }
412
+ catch {
413
+ // A resume of the subagent then gives it nothing again: the rules are in its context already.
414
+ }
415
+ return {
416
+ record: {
417
+ event: 'subagent-rules',
418
+ agent_type: start?.subagent_type ?? call.subagent_type,
419
+ start_match: 'metadata',
420
+ call_id: callId,
421
+ model: call.predicted,
422
+ status: call.status,
423
+ ...(call.rules !== undefined ? { rules: call.rules, sha256: call.sha256 } : {}),
424
+ scope: call.scope ?? null,
425
+ place: 'subagent',
426
+ delivered: 'rules',
427
+ warned: false,
428
+ },
429
+ messages: [],
430
+ specific: { hookEventName: str(input.hook_event_name) ?? 'PostToolUse', additionalContext: call.text },
431
+ };
432
+ }
433
+ function startContext(text) {
434
+ return { hookEventName: 'SubagentStart', additionalContext: text };
435
+ }
436
+ /**
437
+ * The rules a start gives. A start matched with one call gives that call's rules. A shared start gives
438
+ * what every call it could have been would give: their rules when all are the same; when they are for
439
+ * one model but differ by scope, that model's rules for every scope, which each of them holds; and
440
+ * otherwise nothing, so a subagent never gets rules chosen for another subagent.
441
+ */
442
+ function startText(config, taken, state) {
443
+ const calls = taken.calls.map((id) => readAgentCall(agentCallFile(state, id)));
444
+ const give = (c) => (c !== null && c.delivered === 'at-start' && c.text !== undefined ? c.text : null);
445
+ if (taken.match !== 'shared') {
446
+ const c = calls[0] ?? null;
447
+ if (c === null)
448
+ return { text: null, fields: { error: 'the record of the call is missing' }, delivered: 'nothing' };
449
+ return {
450
+ text: give(c),
451
+ fields: {
452
+ model: c.predicted,
453
+ status: c.status,
454
+ ...(c.rules !== undefined ? { rules: c.rules, sha256: c.sha256 } : {}),
455
+ scope: c.scope ?? null,
456
+ place: 'subagent',
457
+ },
458
+ delivered: c.delivered === 'already-delivered' ? 'already-delivered' : 'nothing',
459
+ };
460
+ }
461
+ const texts = calls.map(give);
462
+ const first = calls[0] ?? null;
463
+ if (first !== null && calls.every((c) => c !== null && give(c) === give(first)) && texts[0] !== null)
464
+ return {
465
+ text: texts[0] ?? null,
466
+ fields: { model: first.predicted, status: first.status, rules: first.rules, sha256: first.sha256, scope: first.scope ?? null, place: 'subagent' },
467
+ delivered: 'nothing',
468
+ };
469
+ const models = new Set(calls.map((c) => c?.predicted ?? null));
470
+ const model = models.size === 1 ? ([...models][0] ?? null) : null;
471
+ if (model !== null && texts.every((t) => t !== null)) {
472
+ const common = resolve(config, { model, scope: null, place: 'subagent' });
473
+ if (common.status === 'matched')
474
+ return { text: common.text, fields: { ...decisionFields(common), shared_rules: 'every-scope' }, delivered: 'nothing' };
475
+ }
476
+ const lost = texts.some((t) => t !== null);
477
+ return { text: null, fields: { model, place: 'subagent', ...(lost ? { reason: 'calls-differ' } : {}) }, delivered: 'nothing' };
478
+ }
479
+ /**
480
+ * The pool without the calls that can no longer start: those past the open window, and those made well
481
+ * before the newest open call of their type. A shared group that loses a call this way is dropped with
482
+ * the starts it counted, so a leftover count never settles a later call.
483
+ */
484
+ function current(pool, now) {
485
+ const newest = new Map();
486
+ for (const c of pool.open)
487
+ newest.set(c.type, Math.max(newest.get(c.type) ?? Number.NEGATIVE_INFINITY, Date.parse(c.at)));
488
+ const live = (c) => c.held !== undefined
489
+ ? now - Date.parse(c.held) < HELD_FOR_MS
490
+ : now - Date.parse(c.at) < OPEN_FOR_MS && (newest.get(c.type) ?? 0) - Date.parse(c.at) <= SIBLING_MS;
491
+ const dropped = new Set(pool.open.filter((c) => !live(c)).map((c) => c.id));
492
+ return settled({ open: pool.open.filter(live), groups: pool.groups.filter((g) => !g.calls.some((id) => dropped.has(id))) });
493
+ }
494
+ /** When a group counts as many started subagents as it has open calls, all of them have started. */
495
+ function settled(pool) {
496
+ let open = pool.open;
497
+ const groups = [];
498
+ for (const g of pool.groups) {
499
+ const members = g.calls.filter((id) => open.some((c) => c.id === id));
500
+ if (g.started >= members.length)
501
+ open = open.filter((c) => !members.includes(c.id));
502
+ else if (g.started > 0)
503
+ groups.push({ calls: members, started: g.started });
504
+ }
505
+ return { open, groups };
506
+ }
507
+ function without(pool, id) {
508
+ return settled({ open: pool.open.filter((c) => c.id !== id), groups: pool.groups });
509
+ }
510
+ /** The pool after a shared start among the given calls, counted in one group with any group it overlaps. */
511
+ function withShared(pool, calls) {
512
+ const overlaps = (g) => g.calls.some((id) => calls.includes(id));
513
+ const merged = pool.groups.filter(overlaps);
514
+ const group = {
515
+ calls: [...new Set([...calls, ...merged.flatMap((g) => g.calls)])],
516
+ started: merged.reduce((n, g) => n + g.started, 0) + 1,
517
+ };
518
+ return settled({ open: pool.open, groups: [...pool.groups.filter((g) => !overlaps(g)), group] });
519
+ }
520
+ export function agentResult(input, config, ctx) {
521
+ const response = input.tool_response;
522
+ const r = typeof response === 'object' && response !== null && !Array.isArray(response) ? response : {};
523
+ const subagentId = str(r.agentId);
524
+ const resolved = normalizeModel(str(r.resolvedModel)) || null;
525
+ if (subagentId !== null && resolved !== null) {
526
+ try {
527
+ writeRecord(agentFile(ctx.state, subagentId), { model: resolved, at: ctx.now.toISOString() });
528
+ }
529
+ catch {
530
+ // A call made inside that subagent then reads the subagent's transcript instead.
531
+ }
532
+ }
533
+ const toolUseId = str(input.tool_use_id);
534
+ const callFile = agentCallFile(ctx.state, toolUseId);
535
+ const call = readAgentCall(callFile);
536
+ // No prediction to check: noonsight did not see the call start, or delivery is off.
537
+ if (call === null)
538
+ return null;
539
+ const startFile = agentStartFile(ctx.state, subagentId);
540
+ const sessionId = str(input.session_id);
541
+ // The result names the subagent the call started. A start not seen yet finds its call by it; a
542
+ // shared start among this call's open calls now knows one more of them has started.
543
+ let start = readAgentStart(startFile);
544
+ let linked = false;
545
+ if (toolUseId !== null && sessionId !== null && subagentId !== null && startFile !== null)
546
+ ({ start, linked } = changePool(ctx.state, sessionId, (found) => {
547
+ const pool = current(found, ctx.now.getTime());
548
+ const seen = readAgentStart(startFile);
549
+ if (!pool.open.some((c) => c.id === toolUseId))
550
+ return { pool: null, value: { start: seen, linked: false } };
551
+ const groups = seen?.match === 'shared' ? pool.groups.map((g) => (g.calls.includes(toolUseId) ? { calls: g.calls, started: g.started - 1 } : g)) : pool.groups;
552
+ if (seen === null)
553
+ writeRecord(agentLinkFile(ctx.state, subagentId), { call: toolUseId, at: ctx.now.toISOString() });
554
+ return { pool: without({ open: pool.open, groups }, toolUseId), value: { start: seen, linked: seen === null } };
555
+ }));
556
+ // Kept for a start not seen yet, which reads the rules from it and then removes it.
557
+ if (!linked)
558
+ removeRecord(callFile);
559
+ const result = resolved === null ? 'unknown' : call.predicted === null ? 'unpredicted' : resolved === call.predicted ? 'match' : 'MISMATCH';
560
+ const warn = result === 'MISMATCH' && config.subagents.onMismatch === 'warn';
561
+ const usedModels = Array.isArray(r.modelsUsed) ? r.modelsUsed.filter((m) => typeof m === 'string') : null;
562
+ // What the subagent's start gave it, once seen; before, what its call hands over. A call neither
563
+ // started nor still open, such as one past the open window, gave its subagent nothing.
564
+ const delivered = start !== null ? (start.text !== null ? 'rules' : 'nothing') : !linked && call.delivered === 'at-start' ? 'nothing' : call.delivered;
565
+ const got = delivered !== 'nothing' ? `the rules for ${call.predicted}` : 'no rules';
566
+ return {
567
+ record: {
568
+ subagent_type: call.subagent_type,
569
+ subagent_id: subagentId,
570
+ predicted: call.predicted,
571
+ model: resolved,
572
+ ...(usedModels !== null ? { models_used: usedModels } : {}),
573
+ result,
574
+ delivered,
575
+ ...(call.routing !== undefined ? { routing: call.routing } : {}),
576
+ ...(call.routing_reason !== undefined ? { routing_reason: call.routing_reason } : {}),
577
+ warned: warn,
578
+ },
579
+ messages: warn
580
+ ? [
581
+ `noonsight: subagent ${call.subagent_type}${subagentId !== null ? ` (${subagentId})` : ''} started on ${resolved}, ` +
582
+ `not on ${call.predicted} as noonsight predicted, so it received ${got}.`,
583
+ ]
584
+ : [],
585
+ specific: null,
586
+ };
587
+ }
588
+ /**
589
+ * The model of whoever makes the agent call.
590
+ *
591
+ * A call made inside a subagent carries that subagent's agent_id. Its model is the one noonsight
592
+ * recorded from the result of the call that started it, which for a background subagent arrives at
593
+ * once; for a subagent still running in the foreground, the model of its own transcript.
594
+ *
595
+ * A call made by the session: noonsight's record of the session, kept current by SessionStart and
596
+ * PostModelSwitch; else the session's transcript; else the settings the session started with.
597
+ */
598
+ function parentModel(input, ctx) {
599
+ const sessionId = str(input.session_id);
600
+ const transcript = str(input.transcript_path);
601
+ const agentId = str(input.agent_id);
602
+ if (agentId !== null) {
603
+ const recorded = readAgentModel(agentFile(ctx.state, agentId));
604
+ if (recorded !== null)
605
+ return { model: recorded, source: 'agent-record' };
606
+ const own = transcriptModel(subagentTranscript(transcript, sessionId, agentId), false);
607
+ if (own !== null)
608
+ return { model: own, source: 'agent-transcript' };
609
+ return { model: null, source: null };
610
+ }
611
+ return sessionModel(input, ctx);
612
+ }
613
+ /**
614
+ * The model of the session a hook input comes from: noonsight's record of the session, kept current
615
+ * by SessionStart and PostModelSwitch; else the session's transcript; else the settings the session
616
+ * started with.
617
+ */
618
+ export function sessionModel(input, ctx) {
619
+ const sessionId = str(input.session_id);
620
+ const session = sessionId !== null ? readState(sessionFile(ctx.state, sessionId)) : null;
621
+ if (session?.model)
622
+ return { model: session.model, source: 'session-record' };
623
+ const fromTranscript = transcriptModel(str(input.transcript_path), true);
624
+ if (fromTranscript !== null)
625
+ return { model: fromTranscript, source: 'session-transcript' };
626
+ const launch = launchModel({ env: ctx.env, home: ctx.home, pid: ctx.parentPid, cwd: str(input.cwd) });
627
+ if (launch.kind === 'found')
628
+ return { model: launch.model, source: launch.source };
629
+ return { model: null, source: null };
630
+ }
631
+ function undeclaredMessages(decision, prediction, type, file) {
632
+ if (decision.status !== 'undeclared' || decision.warning === undefined)
633
+ return [];
634
+ if (decision.reason === 'no-entry')
635
+ return [
636
+ `noonsight: subagent ${type} will run on ${decision.model}, which is not declared in ${file}, so it gets no rules. ` +
637
+ 'Declare it under "models" (with "use": "none" if it needs no rules).',
638
+ ];
639
+ return [`noonsight: noonsight cannot tell which model subagent ${type} will run on (${prediction.why ?? 'no model is known'}), so it gets no rules.`];
640
+ }
641
+ export function decisionFields(d) {
642
+ return {
643
+ model: d.model,
644
+ status: d.status,
645
+ ...('reason' in d ? { reason: d.reason } : {}),
646
+ ...('key' in d ? { key: d.key } : {}),
647
+ ...(d.status === 'matched' ? { rules: d.rules, sha256: d.sha256 } : {}),
648
+ ...(d.status === 'matched' && d.triggered !== undefined ? { triggered_rules: d.triggered } : {}),
649
+ scope: d.scope,
650
+ ...(d.unknown_scope !== undefined ? { unknown_scope: d.unknown_scope } : {}),
651
+ place: d.place,
652
+ };
653
+ }
654
+ /** What the decision log records about where the scope and the place came from. */
655
+ export function choiceFields(scope, place) {
656
+ return {
657
+ scope_source: scope.source,
658
+ ...(scope.matcher !== undefined ? { scope_matcher: scope.matcher } : {}),
659
+ ...(place?.because !== undefined ? { unattended_because: place.because } : {}),
660
+ ...(place?.env !== undefined ? { unattended_env: place.env } : {}),
661
+ };
662
+ }
663
+ function str(value) {
664
+ return typeof value === 'string' && value !== '' ? value : null;
665
+ }
666
+ //# sourceMappingURL=subagents.js.map