@crewhaus/runtime-core 0.5.1 → 0.5.3

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 (3) hide show
  1. package/dist/index.d.ts +18 -0
  2. package/dist/index.js +132 -21
  3. package/package.json +40 -40
package/dist/index.d.ts CHANGED
@@ -375,6 +375,24 @@ export type RunChatLoopOptions = {
375
375
  permissionMode?: PermissionMode;
376
376
  /** Layered rule sources. Defaults to `{ ..., builtin: BUILTIN_DEFAULT_RULES }`. */
377
377
  permissionRules?: RuleSet;
378
+ /**
379
+ * #383 — the harness root whose `.crewhaus/settings.json` supplies the
380
+ * `settings`-source permission rules. Every run loads that file at loop
381
+ * start and merges its rules into the `settings` layer (deduped against
382
+ * any settings rules the caller already passed), so operator-persisted
383
+ * standing allows (`crewhaus approvals grant --always`, the Slack "Always
384
+ * allow" button) reach compiled daemons without a recompile. Defaults to
385
+ * `process.cwd()` — the standalone-harness convention. A malformed
386
+ * settings file throws (fail closed, matching the CLI's own reader).
387
+ *
388
+ * `null` DISABLES the load. Sub-agent child loops pass `null`: a child's
389
+ * RuleSet arrives already narrowed by `resolveChildPermissions` from the
390
+ * parent's MERGED rules (the bridge hands the disk-inclusive set to the
391
+ * Task tool), and re-merging the harness file here would let a standing
392
+ * allow in `settings` outrank a replace-mode child's explicit `yaml`
393
+ * deny — widening a deliberately narrowed child.
394
+ */
395
+ settingsDir?: string | null;
378
396
  /**
379
397
  * Install a SIGINT handler that aborts the current turn on first press
380
398
  * and exits on the second. Defaults to true in REPL mode when stdin is
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ import { ConfigError, EXIT_CODES, RunFailedError, RuntimeError, isRunFailedError
14
14
  import { DEFAULT_ROOT_DIR, openEventLog } from "@crewhaus/event-log";
15
15
  import { aggregateDecisions, runHooks } from "@crewhaus/hooks-engine";
16
16
  import { createFailoverChain, createPolicyRouter, createTierRouter, parseModelString, resolveModel, } from "@crewhaus/model-router";
17
- import { BUILTIN_DEFAULT_RULES, emptyRuleSet, evaluateJustification, evaluateWithReason, ruleBasedJustificationJudge, } from "@crewhaus/permission-engine";
17
+ import { BUILTIN_DEFAULT_RULES, emptyRuleSet, evaluateJustification, evaluateWithReason, loadSettingsRules, ruleBasedJustificationJudge, } from "@crewhaus/permission-engine";
18
18
  import { manage as manageCacheMarkers } from "@crewhaus/prompt-cache-manager";
19
19
  import { buildRedactionNotice, classifyText, llmClassifierEnabled, } from "@crewhaus/prompt-injection-detector";
20
20
  import { createRateLimiter } from "@crewhaus/rate-limiter";
@@ -28,6 +28,7 @@ import { createStore } from "@crewhaus/state-store";
28
28
  import { executeStreaming } from "@crewhaus/streaming-tool-executor";
29
29
  import { currentTenantContext } from "@crewhaus/tenancy";
30
30
  import { TokenBudget, estimateTokens } from "@crewhaus/token-budget";
31
+ import { stripJustificationField, withJustificationField } from "@crewhaus/tool-catalog";
31
32
  import { executeTool } from "@crewhaus/tool-executor";
32
33
  import { detectLoop } from "@crewhaus/tool-loop-detection";
33
34
  import { partitionToolCalls } from "@crewhaus/tool-orchestrator";
@@ -145,6 +146,33 @@ function toAnthropicInputSchema(t) {
145
146
  // Degenerate (no object type, no union): coerce to an empty object schema.
146
147
  return { type: "object", properties: converted.properties ?? {} };
147
148
  }
149
+ // Pillar 3 intent gate (#386) — the advertised (model-facing) schema for one
150
+ // registered tool. For `requireJustification` tools the gate reads
151
+ // `input["justification"]`, but models conform tightly to advertised schemas
152
+ // and never invent undeclared fields — so unless the contract is IN the
153
+ // schema, every gated call is denied `justification too brief (0 chars)` and
154
+ // the gate degrades into a hard-off switch (verified live: 12/12 wiki_write
155
+ // calls schema-exact with the field absent even after spec instructions
156
+ // taught it). `withJustificationField` injects a required, described
157
+ // `justification` string property unless the tool's own schema already
158
+ // declares one; `justificationInjected` tells the execute path whether to
159
+ // strip the field back out before the input reaches the tool (remote MCP
160
+ // servers validate against THEIR schema, which may set
161
+ // `additionalProperties: false`). Augmentation runs on the COERCED object
162
+ // schema (after `toAnthropicInputSchema`), so MCP verbatim schemas, flattened
163
+ // unions, and degenerate schemas are all covered, and it copies rather than
164
+ // mutates — `t.jsonSchema` may pass through `toAnthropicInputSchema` by
165
+ // reference and is hashed elsewhere for schema-drift detection.
166
+ function toAdvertisedTool(t) {
167
+ const base = toAnthropicInputSchema(t);
168
+ if (t.requireJustification !== true)
169
+ return { inputSchema: base, justificationInjected: false };
170
+ const { schema, injected } = withJustificationField(base);
171
+ return {
172
+ inputSchema: schema,
173
+ justificationInjected: injected,
174
+ };
175
+ }
148
176
  // Merge a top-level union of object branches into a single object schema.
149
177
  // Anthropic forbids a top-level `anyOf`, but a nested `anyOf` on an individual
150
178
  // property is fine — so each property becomes the union of its per-branch
@@ -1546,10 +1574,32 @@ export async function runChatLoop(opts) {
1546
1574
  ...(curateConfig !== undefined ? { curate: curateConfig, onCurate: publishCurate } : {}),
1547
1575
  });
1548
1576
  const permissionMode = opts.permissionMode ?? "default";
1549
- const permissionRules = opts.permissionRules ?? {
1550
- ...emptyRuleSet,
1551
- builtin: BUILTIN_DEFAULT_RULES,
1552
- };
1577
+ // #383 — merge the harness's `.crewhaus/settings.json` rules into the
1578
+ // `settings` layer. Compiled bundles emit `settings: []`, so without this
1579
+ // load an operator-persisted standing allow (`approvals grant --always`)
1580
+ // could never reach a daemon; interpreter paths (the CLI) already read the
1581
+ // same file themselves, which the (type, pattern) dedupe absorbs. Loaded
1582
+ // once per run — a park ends the run, so the re-driven run re-reads it.
1583
+ // `settingsDir: null` (sub-agent child loops) skips the load entirely.
1584
+ const permissionRules = (() => {
1585
+ const base = opts.permissionRules ?? {
1586
+ ...emptyRuleSet,
1587
+ builtin: BUILTIN_DEFAULT_RULES,
1588
+ };
1589
+ if (opts.settingsDir === null)
1590
+ return base;
1591
+ const diskSettings = loadSettingsRules(opts.settingsDir ?? process.cwd());
1592
+ if (diskSettings.length === 0)
1593
+ return base;
1594
+ const seen = new Set(base.settings.map((r) => `${r.type}${r.pattern}`));
1595
+ return {
1596
+ ...base,
1597
+ settings: [
1598
+ ...base.settings,
1599
+ ...diskSettings.filter((r) => !seen.has(`${r.type}${r.pattern}`)),
1600
+ ],
1601
+ };
1602
+ })();
1553
1603
  const userInstructions = {
1554
1604
  type: "text",
1555
1605
  text: opts.instructions,
@@ -1734,13 +1784,40 @@ export async function runChatLoop(opts) {
1734
1784
  }
1735
1785
  }
1736
1786
  const tools = effectiveTools;
1737
- const anthropicTools = tools.length > 0
1738
- ? tools.map((t) => ({
1739
- name: t.name,
1740
- description: t.description,
1741
- input_schema: toAnthropicInputSchema(t),
1787
+ // (#386) — advertise each tool's model-facing schema, with the intent
1788
+ // gate's `justification` contract injected for `requireJustification`
1789
+ // tools whose own schema doesn't declare it (see `toAdvertisedTool`).
1790
+ const advertisedTools = tools.map((t) => ({ tool: t, advertised: toAdvertisedTool(t) }));
1791
+ const anthropicTools = advertisedTools.length > 0
1792
+ ? advertisedTools.map(({ tool, advertised }) => ({
1793
+ name: tool.name,
1794
+ description: tool.description,
1795
+ input_schema: advertised.inputSchema,
1742
1796
  }))
1743
1797
  : undefined;
1798
+ // (#386) — tools whose advertised schema carries a RUNTIME-INJECTED
1799
+ // justification property. For exactly these, the field is gate metadata
1800
+ // rather than tool input — the underlying validator/server never declared
1801
+ // it (a remote MCP server with `additionalProperties: false` would reject
1802
+ // the call) — so every surface that reasons about WHAT THE TOOL DOES
1803
+ // consumes the OPERATIVE input (justification stripped) while the
1804
+ // surfaces that reason about WHAT THE MODEL DID keep the full input.
1805
+ // Operative-input consumers: permission-rule matching (arg-scoped
1806
+ // `Tool(argGlob)` rules must keep matching the way they did before the
1807
+ // field existed), the headless approval `inputHash` (a one-shot grant must
1808
+ // be consumable by a regenerated call whose operative args are identical
1809
+ // even though the re-worded justification is not), tool-loop detection
1810
+ // history (re-worded justifications must not make identical calls hash
1811
+ // apart), the egress classifier (scan what is actually transmitted), and
1812
+ // the tool executor itself. Full-input consumers: the event log, trace
1813
+ // bus, pre-tool hooks, the approval record's display `input`, the
1814
+ // justification gate, and the justification audit sink. Tools that
1815
+ // declare the field in their own schema are NOT in this set — for them
1816
+ // the field is genuine tool input everywhere.
1817
+ const justificationInjectedTools = new Set(advertisedTools
1818
+ .filter(({ advertised }) => advertised.justificationInjected)
1819
+ .map(({ tool }) => tool.name));
1820
+ const operativeToolInput = (name, input) => justificationInjectedTools.has(name) ? stripJustificationField(input) : input;
1744
1821
  const toolByName = new Map(tools.map((t) => [t.name, t]));
1745
1822
  // G17 — per-tool rate limiter, built once at loop start from the lowered
1746
1823
  // `agent.rate_limits` map. One token bucket per entry: `rpm` is the
@@ -1989,9 +2066,16 @@ export async function runChatLoop(opts) {
1989
2066
  is_error: true,
1990
2067
  });
1991
2068
  }
2069
+ // (#386) — the operative input for this call: for tools whose advertised
2070
+ // schema carries a runtime-injected justification, the field is stripped
2071
+ // here once and every surface below that reasons about what the tool
2072
+ // DOES (rule matching, approval hashing, egress, execution) consumes
2073
+ // this; surfaces that record what the model DID keep `tu.input`. See the
2074
+ // `justificationInjectedTools` comment at loop start for the full split.
2075
+ const operativeInput = operativeToolInput(tu.name, tu.input);
1992
2076
  const decisionDetails = evaluateWithReason({
1993
2077
  toolName: tu.name,
1994
- input: tu.input,
2078
+ input: operativeInput,
1995
2079
  readOnly: tool.readOnly,
1996
2080
  destructive: tool.destructive,
1997
2081
  requiresSandbox: tool.requiresSandbox,
@@ -2019,11 +2103,23 @@ export async function runChatLoop(opts) {
2019
2103
  }
2020
2104
  else if (approvals !== undefined && askMode === "pause") {
2021
2105
  // G11 headless parking/resume. Consult the store for a prior decision
2022
- // on this exact (toolName, inputHash).
2023
- const inputHash = hashApprovalInput(tu.name, tu.input);
2106
+ // on this exact (toolName, inputHash). The hash keys on the OPERATIVE
2107
+ // input (#386): a runtime-injected justification is re-worded by the
2108
+ // model on every regeneration, so hashing it would make a granted
2109
+ // approval unconsumable — the rerun would park a fresh approval
2110
+ // forever. The persisted record still carries the full `tu.input`
2111
+ // below so the approving operator SEES the justification.
2112
+ const inputHash = hashApprovalInput(tu.name, operativeInput);
2024
2113
  const existing = await approvals.store.get(tu.name, inputHash);
2025
2114
  if (existing?.decision === "grant") {
2026
- // One-shot allow: consume the grant so a later identical call re-asks.
2115
+ // One-shot allow: consume the grant so a later identical call
2116
+ // re-asks. A STANDING grant (#383, `existing.always`) is consumed
2117
+ // the same way — its standing behavior rides the settings-source
2118
+ // `alwaysAllow` rule the resolving surface persisted, which
2119
+ // pre-decides future calls before this store is ever consulted.
2120
+ // Keeping consumption uniform means deleting that rule fully
2121
+ // revokes the standing allow (no unconsumed record lingers to
2122
+ // pre-approve the parked input until the TTL sweep).
2027
2123
  approved = true;
2028
2124
  await approvals.store.persist({ ...existing, consumedAt: new Date().toISOString() });
2029
2125
  }
@@ -2076,7 +2172,7 @@ export async function runChatLoop(opts) {
2076
2172
  class: "approval_pending",
2077
2173
  title: "awaiting tool approval",
2078
2174
  detail: `\`${tu.name}\` requires approval on a non-interactive surface (${approvalSurface}); the run is parked as approval ${pending.id}`,
2079
- remediation: `grant or deny approval ${pending.id} out of band (e.g. \`crewhaus approvals grant ${pending.id}\`), then rerun`,
2175
+ remediation: `grant or deny approval ${pending.id} out of band (e.g. \`crewhaus approvals grant ${pending.id}\`; add \`--always\` to allow \`${tu.name}\` from now on), then rerun`,
2080
2176
  exitCode: EXIT_CODES.approval_pending,
2081
2177
  });
2082
2178
  }
@@ -2192,7 +2288,7 @@ export async function runChatLoop(opts) {
2192
2288
  return finish({
2193
2289
  type: "tool_result",
2194
2290
  tool_use_id: tu.id,
2195
- content: `[justification denied] ${verdict.reason}. Reformulate the call with a justification that ties to the session's declared goal, or omit this tool from the call.`,
2291
+ content: `[justification denied] ${verdict.reason}. Reformulate the call with a \`justification\` string field in the tool input that ties to the session's declared goal, or omit this tool from the call.`,
2196
2292
  is_error: true,
2197
2293
  });
2198
2294
  }
@@ -2209,7 +2305,9 @@ export async function runChatLoop(opts) {
2209
2305
  // `"external-configured"` (warn). Callers can override via
2210
2306
  // `opts.resolveSinkScope` to mark federation-joined or other dynamic sinks.
2211
2307
  if (tool.scope === "external") {
2212
- const payload = JSON.stringify(tu.input ?? null);
2308
+ // (#386) — scan the OPERATIVE payload: for injected-justification
2309
+ // tools this is what `executeTool` actually transmits to the sink.
2310
+ const payload = JSON.stringify(operativeInput ?? null);
2213
2311
  const sinkScope = (opts.resolveSinkScope ?? defaultSinkScope)(tu.name);
2214
2312
  const egress = await classifyEgress(payload, runContext, {
2215
2313
  sinkId: tu.name,
@@ -2356,7 +2454,7 @@ export async function runChatLoop(opts) {
2356
2454
  // every gate (permission/justification/egress) so it never overlaps the
2357
2455
  // approval prompt, and torn down in `.finally` on success or throw.
2358
2456
  beginToolWork(tu.name);
2359
- const raw = await executeTool(tool, tu.input, {
2457
+ const raw = await executeTool(tool, operativeInput, {
2360
2458
  toolUseId: tu.id,
2361
2459
  signal: toolAbort.signal,
2362
2460
  // #160 follow-up — the bridge (built on every run, above) carries
@@ -3076,7 +3174,15 @@ export async function runChatLoop(opts) {
3076
3174
  // Item 26 — accrue this turn's tool_use count (next-turn tier signal).
3077
3175
  thisTurnToolUseCount += toolUses.length;
3078
3176
  for (const tu of toolUses) {
3079
- toolUseHistory.push({ id: tu.id, name: tu.name, input: tu.input });
3177
+ // (#386) — loop detection compares OPERATIVE inputs: a
3178
+ // runtime-injected justification is re-worded every call, so
3179
+ // recording it would make identical gated calls hash apart
3180
+ // and hide exactly the loops the detector exists to catch.
3181
+ toolUseHistory.push({
3182
+ id: tu.id,
3183
+ name: tu.name,
3184
+ input: operativeToolInput(tu.name, tu.input),
3185
+ });
3080
3186
  }
3081
3187
  messages.push({ role: "user", content: [...toolResults] });
3082
3188
  await logEvent("user_message", { content: [...toolResults] });
@@ -3221,8 +3327,13 @@ export async function runChatLoop(opts) {
3221
3327
  name: t.name,
3222
3328
  input: t.input,
3223
3329
  }));
3224
- for (const tu of tsmBlocks)
3225
- toolUseHistory.push(tu);
3330
+ // (#386) — history records the OPERATIVE input (injected
3331
+ // justification stripped) so re-worded justifications don't
3332
+ // hide loops; `tsmBlocks` itself stays full-input because it
3333
+ // flows on to `executeOneToolUse`, whose gate reads the field.
3334
+ for (const tu of tsmBlocks) {
3335
+ toolUseHistory.push({ ...tu, input: operativeToolInput(tu.name, tu.input) });
3336
+ }
3226
3337
  // Item 7 — the response fully drained (usage known) before these
3227
3338
  // calls dispatch in `NeedTools`, so the split IS computable here:
3228
3339
  // split the priceable response cost evenly across its tool_use
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/runtime-core",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "type": "module",
5
5
  "description": "Minimal runtime imported by generated harness bundles",
6
6
  "main": "dist/index.js",
@@ -16,45 +16,45 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "@anthropic-ai/sdk": "^0.96.0",
19
- "@crewhaus/abort-controller": "0.5.1",
20
- "@crewhaus/adapter-anthropic": "0.5.1",
21
- "@crewhaus/agent-context-isolation": "0.5.1",
22
- "@crewhaus/boundary-classifier": "0.5.1",
23
- "@crewhaus/circuit-breaker": "0.5.1",
24
- "@crewhaus/compaction-autocompact": "0.5.1",
25
- "@crewhaus/compaction-curator": "0.5.1",
26
- "@crewhaus/compaction-snip": "0.5.1",
27
- "@crewhaus/cost-tracker": "0.5.1",
28
- "@crewhaus/egress-classifier": "0.5.1",
29
- "@crewhaus/errors": "0.5.1",
30
- "@crewhaus/event-log": "0.5.1",
31
- "@crewhaus/hooks-engine": "0.5.1",
32
- "@crewhaus/model-router": "0.5.1",
33
- "@crewhaus/permission-engine": "0.5.1",
34
- "@crewhaus/prompt-cache-manager": "0.5.1",
35
- "@crewhaus/prompt-injection-detector": "0.5.1",
36
- "@crewhaus/rate-limiter": "0.5.1",
37
- "@crewhaus/recovery-engine": "0.5.1",
38
- "@crewhaus/routing-store": "0.5.1",
39
- "@crewhaus/run-context": "0.5.1",
40
- "@crewhaus/session-store": "0.5.1",
41
- "@crewhaus/skills-registry": "0.5.1",
42
- "@crewhaus/slash-commands": "0.5.1",
43
- "@crewhaus/state-store": "0.5.1",
44
- "@crewhaus/tenancy": "0.5.1",
45
- "@crewhaus/token-budget": "0.5.1",
46
- "@crewhaus/tool-catalog": "0.5.1",
47
- "@crewhaus/tool-executor": "0.5.1",
48
- "@crewhaus/tool-loop-detection": "0.5.1",
49
- "@crewhaus/tool-orchestrator": "0.5.1",
50
- "@crewhaus/tool-result-store": "0.5.1",
51
- "@crewhaus/streaming-tool-executor": "0.5.1",
52
- "@crewhaus/turn-state-machine": "0.5.1",
53
- "@crewhaus/trace-event-bus": "0.5.1",
54
- "@crewhaus/worker-runtime": "0.5.1",
55
- "@crewhaus/structured-event-printer": "0.5.1",
56
- "@crewhaus/metrics-collector": "0.5.1",
57
- "@crewhaus/otel-exporter": "0.5.1",
19
+ "@crewhaus/abort-controller": "0.5.3",
20
+ "@crewhaus/adapter-anthropic": "0.5.3",
21
+ "@crewhaus/agent-context-isolation": "0.5.3",
22
+ "@crewhaus/boundary-classifier": "0.5.3",
23
+ "@crewhaus/circuit-breaker": "0.5.3",
24
+ "@crewhaus/compaction-autocompact": "0.5.3",
25
+ "@crewhaus/compaction-curator": "0.5.3",
26
+ "@crewhaus/compaction-snip": "0.5.3",
27
+ "@crewhaus/cost-tracker": "0.5.3",
28
+ "@crewhaus/egress-classifier": "0.5.3",
29
+ "@crewhaus/errors": "0.5.3",
30
+ "@crewhaus/event-log": "0.5.3",
31
+ "@crewhaus/hooks-engine": "0.5.3",
32
+ "@crewhaus/model-router": "0.5.3",
33
+ "@crewhaus/permission-engine": "0.5.3",
34
+ "@crewhaus/prompt-cache-manager": "0.5.3",
35
+ "@crewhaus/prompt-injection-detector": "0.5.3",
36
+ "@crewhaus/rate-limiter": "0.5.3",
37
+ "@crewhaus/recovery-engine": "0.5.3",
38
+ "@crewhaus/routing-store": "0.5.3",
39
+ "@crewhaus/run-context": "0.5.3",
40
+ "@crewhaus/session-store": "0.5.3",
41
+ "@crewhaus/skills-registry": "0.5.3",
42
+ "@crewhaus/slash-commands": "0.5.3",
43
+ "@crewhaus/state-store": "0.5.3",
44
+ "@crewhaus/tenancy": "0.5.3",
45
+ "@crewhaus/token-budget": "0.5.3",
46
+ "@crewhaus/tool-catalog": "0.5.3",
47
+ "@crewhaus/tool-executor": "0.5.3",
48
+ "@crewhaus/tool-loop-detection": "0.5.3",
49
+ "@crewhaus/tool-orchestrator": "0.5.3",
50
+ "@crewhaus/tool-result-store": "0.5.3",
51
+ "@crewhaus/streaming-tool-executor": "0.5.3",
52
+ "@crewhaus/turn-state-machine": "0.5.3",
53
+ "@crewhaus/trace-event-bus": "0.5.3",
54
+ "@crewhaus/worker-runtime": "0.5.3",
55
+ "@crewhaus/structured-event-printer": "0.5.3",
56
+ "@crewhaus/metrics-collector": "0.5.3",
57
+ "@crewhaus/otel-exporter": "0.5.3",
58
58
  "zod-to-json-schema": "^3.23.5"
59
59
  },
60
60
  "devDependencies": {