@hmharness/kernel 0.9.2 → 0.9.4

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.
@@ -0,0 +1,114 @@
1
+ /**
2
+ * @hmharness/kernel - Capability Plane v1 (P0-02, 2026-09-24 audit)
3
+ *
4
+ * The unified capability model: every side effect the agent can cause -
5
+ * native tools, MCP tools, skills, device actions - maps to the same
6
+ * CapabilityManifest and passes through the same PolicyEngine. No tool
7
+ * gets special treatment; the security perimeter is one plane.
8
+ *
9
+ * This is the ADR-0012 foundation the audit called for: "Native Tool,
10
+ * MCP Tool, Skill, Device Action 全都映射成同一个 Capability 模型,
11
+ * 并由同一个 PolicyEngine 鉴权".
12
+ */
13
+ /** Risk classification drives the approval tier, not the tool name. */
14
+ export type CapabilityRisk = 'read-only' | 'workspace-write' | 'network' | 'system' | 'destructive' | 'device';
15
+ /** Where the capability came from - supply-chain provenance matters. */
16
+ export type CapabilitySource = 'builtin' | 'mcp' | 'skill' | 'device' | 'plugin';
17
+ export interface CapabilityManifest {
18
+ /** unique id: namespace:name (e.g. "fs:read_file", "mcp:context7:search") */
19
+ id: string;
20
+ /** what this capability does, for audit and policy matching */
21
+ description: string;
22
+ /** risk tier - the ONLY thing that determines approval requirements */
23
+ risk: CapabilityRisk;
24
+ /** origin provenance */
25
+ source: CapabilitySource;
26
+ /** the actual executor function (internal use) */
27
+ handler?: string;
28
+ /** parameter schema (JSON Schema subset) */
29
+ params?: Record<string, unknown>;
30
+ /** side effects this capability can cause (for audit trail) */
31
+ sideEffects?: string[];
32
+ /** version of this capability definition */
33
+ version: string;
34
+ }
35
+ export interface PolicyDecision {
36
+ allow: boolean;
37
+ reason: string;
38
+ /** if allow=true but requires user confirmation */
39
+ needsApproval: boolean;
40
+ /** policy that made the decision (for audit) */
41
+ policyId: string;
42
+ }
43
+ /**
44
+ * Policy rules are declarative and versioned. A rule matches on capability
45
+ * properties (risk, source, id prefix) and produces a decision. Rules are
46
+ * evaluated in order; the first matching rule wins.
47
+ */
48
+ export interface PolicyRule {
49
+ id: string;
50
+ /** match conditions (all must be true) */
51
+ match: {
52
+ risk?: CapabilityRisk | CapabilityRisk[];
53
+ source?: CapabilitySource | CapabilitySource[];
54
+ /** id prefix match (e.g. "fs:" matches all filesystem tools) */
55
+ idPrefix?: string;
56
+ };
57
+ decision: {
58
+ allow: boolean;
59
+ needsApproval: boolean;
60
+ reason: string;
61
+ };
62
+ priority: number;
63
+ }
64
+ /**
65
+ * The default policy: secure-by-default, deny-first.
66
+ * Read-only operations are allowed without approval.
67
+ * Everything else requires explicit user consent.
68
+ */
69
+ export declare const DEFAULT_POLICY_RULES: PolicyRule[];
70
+ /**
71
+ * The CapabilityRegistry holds all registered capabilities and evaluates
72
+ * policy decisions. It is the single entry point for "can the agent do X?"
73
+ */
74
+ export declare class CapabilityRegistry {
75
+ private capabilities;
76
+ private rules;
77
+ constructor(rules?: PolicyRule[]);
78
+ /** Register a capability. Duplicate ids are rejected (supply-chain safety). */
79
+ register(manifest: CapabilityManifest): {
80
+ ok: boolean;
81
+ reason?: string;
82
+ };
83
+ /** Check if a capability exists. */
84
+ has(id: string): boolean;
85
+ /** Get a capability manifest. */
86
+ get(id: string): CapabilityManifest | undefined;
87
+ /** List all capabilities, optionally filtered. */
88
+ list(filter?: {
89
+ risk?: CapabilityRisk;
90
+ source?: CapabilitySource;
91
+ }): CapabilityManifest[];
92
+ /**
93
+ * Evaluate policy for a capability. This is THE gate every tool call
94
+ * passes through - no exceptions, no bypass paths.
95
+ */
96
+ check(id: string): PolicyDecision;
97
+ private matchesRule;
98
+ /**
99
+ * Add a custom policy rule (for user overrides via config).
100
+ * Custom rules are inserted at the specified priority.
101
+ */
102
+ addRule(rule: PolicyRule): void;
103
+ /** Export the audit trail: all capabilities + their current policy decisions. */
104
+ audit(): Array<{
105
+ manifest: CapabilityManifest;
106
+ decision: PolicyDecision;
107
+ }>;
108
+ }
109
+ /**
110
+ * Helper to classify tool risk from the existing tool registry.
111
+ * Maps hmharness's current `needsApproval` + tool names to the new
112
+ * CapabilityRisk tiers.
113
+ */
114
+ export declare function classifyToolRisk(name: string, needsApproval: boolean): CapabilityRisk;
@@ -0,0 +1,178 @@
1
+ /**
2
+ * @hmharness/kernel - Capability Plane v1 (P0-02, 2026-09-24 audit)
3
+ *
4
+ * The unified capability model: every side effect the agent can cause -
5
+ * native tools, MCP tools, skills, device actions - maps to the same
6
+ * CapabilityManifest and passes through the same PolicyEngine. No tool
7
+ * gets special treatment; the security perimeter is one plane.
8
+ *
9
+ * This is the ADR-0012 foundation the audit called for: "Native Tool,
10
+ * MCP Tool, Skill, Device Action 全都映射成同一个 Capability 模型,
11
+ * 并由同一个 PolicyEngine 鉴权".
12
+ */
13
+ /**
14
+ * The default policy: secure-by-default, deny-first.
15
+ * Read-only operations are allowed without approval.
16
+ * Everything else requires explicit user consent.
17
+ */
18
+ export const DEFAULT_POLICY_RULES = [
19
+ {
20
+ id: 'deny-destructive',
21
+ priority: 0,
22
+ match: { risk: 'destructive' },
23
+ decision: { allow: false, needsApproval: false, reason: 'destructive operations are denied by default' },
24
+ },
25
+ {
26
+ id: 'approve-system',
27
+ priority: 10,
28
+ match: { risk: 'system' },
29
+ decision: { allow: true, needsApproval: true, reason: 'system-level operations require approval' },
30
+ },
31
+ {
32
+ id: 'approve-network',
33
+ priority: 20,
34
+ match: { risk: 'network' },
35
+ decision: { allow: true, needsApproval: true, reason: 'network access requires approval' },
36
+ },
37
+ {
38
+ id: 'approve-device',
39
+ priority: 30,
40
+ match: { risk: 'device' },
41
+ decision: { allow: true, needsApproval: true, reason: 'device operations require approval' },
42
+ },
43
+ {
44
+ id: 'approve-workspace-write',
45
+ priority: 40,
46
+ match: { risk: 'workspace-write' },
47
+ decision: { allow: true, needsApproval: true, reason: 'workspace modifications require approval' },
48
+ },
49
+ {
50
+ id: 'approve-plugin',
51
+ priority: 50,
52
+ match: { source: 'plugin' },
53
+ decision: { allow: true, needsApproval: true, reason: 'third-party plugins require approval' },
54
+ },
55
+ {
56
+ id: 'allow-readonly',
57
+ priority: 100,
58
+ match: { risk: 'read-only' },
59
+ decision: { allow: true, needsApproval: false, reason: 'read-only operations are safe' },
60
+ },
61
+ {
62
+ id: 'deny-unknown',
63
+ priority: 999,
64
+ match: {},
65
+ decision: { allow: false, needsApproval: false, reason: 'unclassified capabilities are denied (deny-first)' },
66
+ },
67
+ ];
68
+ /**
69
+ * The CapabilityRegistry holds all registered capabilities and evaluates
70
+ * policy decisions. It is the single entry point for "can the agent do X?"
71
+ */
72
+ export class CapabilityRegistry {
73
+ capabilities = new Map();
74
+ rules;
75
+ constructor(rules = DEFAULT_POLICY_RULES) {
76
+ this.rules = [...rules].sort((a, b) => a.priority - b.priority);
77
+ }
78
+ /** Register a capability. Duplicate ids are rejected (supply-chain safety). */
79
+ register(manifest) {
80
+ if (this.capabilities.has(manifest.id)) {
81
+ return { ok: false, reason: `capability ${manifest.id} already registered (deny overwrite for supply-chain safety)` };
82
+ }
83
+ this.capabilities.set(manifest.id, manifest);
84
+ return { ok: true };
85
+ }
86
+ /** Check if a capability exists. */
87
+ has(id) {
88
+ return this.capabilities.has(id);
89
+ }
90
+ /** Get a capability manifest. */
91
+ get(id) {
92
+ return this.capabilities.get(id);
93
+ }
94
+ /** List all capabilities, optionally filtered. */
95
+ list(filter) {
96
+ const all = [...this.capabilities.values()];
97
+ if (!filter)
98
+ return all;
99
+ return all.filter(c => (!filter.risk || c.risk === filter.risk) &&
100
+ (!filter.source || c.source === filter.source));
101
+ }
102
+ /**
103
+ * Evaluate policy for a capability. This is THE gate every tool call
104
+ * passes through - no exceptions, no bypass paths.
105
+ */
106
+ check(id) {
107
+ const cap = this.capabilities.get(id);
108
+ if (!cap) {
109
+ return { allow: false, reason: `capability ${id} not registered`, needsApproval: false, policyId: 'not-found' };
110
+ }
111
+ for (const rule of this.rules) {
112
+ if (this.matchesRule(cap, rule)) {
113
+ return {
114
+ allow: rule.decision.allow,
115
+ needsApproval: rule.decision.needsApproval,
116
+ reason: rule.decision.reason,
117
+ policyId: rule.id,
118
+ };
119
+ }
120
+ }
121
+ return { allow: false, reason: 'no matching policy rule', needsApproval: false, policyId: 'no-match' };
122
+ }
123
+ matchesRule(cap, rule) {
124
+ const m = rule.match;
125
+ if (m.risk) {
126
+ const risks = Array.isArray(m.risk) ? m.risk : [m.risk];
127
+ if (!risks.includes(cap.risk))
128
+ return false;
129
+ }
130
+ if (m.source) {
131
+ const sources = Array.isArray(m.source) ? m.source : [m.source];
132
+ if (!sources.includes(cap.source))
133
+ return false;
134
+ }
135
+ if (m.idPrefix && !cap.id.startsWith(m.idPrefix))
136
+ return false;
137
+ return true;
138
+ }
139
+ /**
140
+ * Add a custom policy rule (for user overrides via config).
141
+ * Custom rules are inserted at the specified priority.
142
+ */
143
+ addRule(rule) {
144
+ this.rules.push(rule);
145
+ this.rules.sort((a, b) => a.priority - b.priority);
146
+ }
147
+ /** Export the audit trail: all capabilities + their current policy decisions. */
148
+ audit() {
149
+ return [...this.capabilities.values()].map(m => ({ manifest: m, decision: this.check(m.id) }));
150
+ }
151
+ }
152
+ /**
153
+ * Helper to classify tool risk from the existing tool registry.
154
+ * Maps hmharness's current `needsApproval` + tool names to the new
155
+ * CapabilityRisk tiers.
156
+ */
157
+ export function classifyToolRisk(name, needsApproval) {
158
+ const lower = name.toLowerCase();
159
+ // destructive patterns (hardcoded deny in existing kernel)
160
+ if (/rm\s+-rf|del\s+\/[sq]|format|mkfs|dd\s+if=/.test(lower))
161
+ return 'destructive';
162
+ if (/reset\s+--hard|force\s+push|clean\s+-xfd/.test(lower))
163
+ return 'destructive';
164
+ // device operations
165
+ if (/hdc|emulator|device|install|uninstall|launch/.test(lower))
166
+ return 'device';
167
+ // network access
168
+ if (/fetch|web_search|http|url|curl|wget|api/.test(lower))
169
+ return 'network';
170
+ // system-level
171
+ if (/shell|exec|spawn|command|process|kill|taskkill|npm\s+install/.test(lower))
172
+ return 'system';
173
+ // workspace writes
174
+ if (/write|edit|create|mkdir|move|copy|patch/.test(lower))
175
+ return 'workspace-write';
176
+ // read-only by default
177
+ return needsApproval ? 'workspace-write' : 'read-only';
178
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './types.ts';
2
2
  export * from './shellgate.ts';
3
+ export * from './capability.ts';
3
4
  export * from './registry.ts';
4
5
  export * from './provider.ts';
5
6
  export * from './window.ts';
@@ -10,3 +11,4 @@ export * from './config.ts';
10
11
  export * from './context.ts';
11
12
  export * from './mcp.ts';
12
13
  export * from './goal.ts';
14
+ export * from './mcp2026.ts';
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./types.js";
2
2
  export * from "./shellgate.js";
3
+ export * from "./capability.js";
3
4
  export * from "./registry.js";
4
5
  export * from "./provider.js";
5
6
  export * from "./window.js";
@@ -10,3 +11,4 @@ export * from "./config.js";
10
11
  export * from "./context.js";
11
12
  export * from "./mcp.js";
12
13
  export * from "./goal.js";
14
+ export * from "./mcp2026.js";
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @hmharness/kernel - MCP 2026-07-28 Conformance (P0-03)
3
+ *
4
+ * Updates the MCP client to conform to the 2026-07-28 specification:
5
+ * 1. Stateless core: operations don't require session state
6
+ * 2. Header-based routing: Mcp-Session-Id, Mcp-Protocol-Version headers
7
+ * 3. Tasks extension: long-running task lifecycle management
8
+ * 4. Authorization hardening: per-request auth validation
9
+ * 5. Cacheable list results: ETag/If-None-Match for tools/resources lists
10
+ *
11
+ * Reference: https://modelcontextprotocol.io/specification/2025-11-25
12
+ * (2026-07-28 is the latest ratification with these additions)
13
+ */
14
+ /** MCP protocol version we conform to */
15
+ export declare const MCP_PROTOCOL_VERSION = "2026-07-28";
16
+ /** Headers defined by the 2026-07-28 spec */
17
+ export declare const MCP_HEADERS: {
18
+ readonly sessionId: "Mcp-Session-Id";
19
+ readonly protocolVersion: "Mcp-Protocol-Version";
20
+ readonly lastEventId: "Last-Event-Id";
21
+ };
22
+ /** Task lifecycle states (Tasks extension) */
23
+ export type McpTaskStatus = 'submitted' | 'working' | 'input-required' | 'completed' | 'cancelled' | 'failed';
24
+ export interface McpTask {
25
+ id: string;
26
+ status: McpTaskStatus;
27
+ result?: unknown;
28
+ createdAt: string;
29
+ updatedAt: string;
30
+ }
31
+ /**
32
+ * Build headers for an MCP request per the 2026-07-28 spec.
33
+ * Pure - testable.
34
+ */
35
+ export declare function buildMcpHeaders(opts: {
36
+ sessionId?: string;
37
+ protocolVersion?: string;
38
+ lastEventId?: string;
39
+ authorization?: string;
40
+ }): Record<string, string>;
41
+ /**
42
+ * Validate MCP response headers for protocol compliance.
43
+ * Pure - testable.
44
+ */
45
+ export declare function validateMcpResponseHeaders(headers: Record<string, string>): {
46
+ valid: boolean;
47
+ issues: string[];
48
+ sessionId?: string;
49
+ };
50
+ /**
51
+ * Determine if a tools/resources list response can be cached.
52
+ * The 2026-07-28 spec makes list results cacheable via ETag.
53
+ * Pure - testable.
54
+ */
55
+ export declare function isCacheableListResponse(headers: Record<string, string>): {
56
+ cacheable: boolean;
57
+ etag?: string;
58
+ };
59
+ /**
60
+ * Build a conditional list request using a cached ETag.
61
+ * Pure - testable.
62
+ */
63
+ export declare function buildConditionalListRequest(cachedEtag?: string): Record<string, string>;
64
+ /**
65
+ * Check if an HTTP 304 response means the cached list is still valid.
66
+ * Pure - testable.
67
+ */
68
+ export declare function isNotModified(status: number): boolean;
69
+ /**
70
+ * Task state machine per the Tasks extension.
71
+ * Pure - testable.
72
+ */
73
+ export declare function canTransitionTask(from: McpTaskStatus, to: McpTaskStatus): boolean;
74
+ /**
75
+ * Authorization check per the 2026-07-28 hardening requirements.
76
+ * Pure - testable.
77
+ */
78
+ export declare function validateMcpAuth(config: {
79
+ type: 'stdio' | 'http';
80
+ headers?: Record<string, string>;
81
+ }): {
82
+ authorized: boolean;
83
+ reason: string;
84
+ };
@@ -0,0 +1,112 @@
1
+ /**
2
+ * @hmharness/kernel - MCP 2026-07-28 Conformance (P0-03)
3
+ *
4
+ * Updates the MCP client to conform to the 2026-07-28 specification:
5
+ * 1. Stateless core: operations don't require session state
6
+ * 2. Header-based routing: Mcp-Session-Id, Mcp-Protocol-Version headers
7
+ * 3. Tasks extension: long-running task lifecycle management
8
+ * 4. Authorization hardening: per-request auth validation
9
+ * 5. Cacheable list results: ETag/If-None-Match for tools/resources lists
10
+ *
11
+ * Reference: https://modelcontextprotocol.io/specification/2025-11-25
12
+ * (2026-07-28 is the latest ratification with these additions)
13
+ */
14
+ /** MCP protocol version we conform to */
15
+ export const MCP_PROTOCOL_VERSION = '2026-07-28';
16
+ /** Headers defined by the 2026-07-28 spec */
17
+ export const MCP_HEADERS = {
18
+ sessionId: 'Mcp-Session-Id',
19
+ protocolVersion: 'Mcp-Protocol-Version',
20
+ lastEventId: 'Last-Event-Id',
21
+ };
22
+ /**
23
+ * Build headers for an MCP request per the 2026-07-28 spec.
24
+ * Pure - testable.
25
+ */
26
+ export function buildMcpHeaders(opts) {
27
+ const headers = {
28
+ 'Content-Type': 'application/json',
29
+ [MCP_HEADERS.protocolVersion]: opts.protocolVersion ?? MCP_PROTOCOL_VERSION,
30
+ };
31
+ if (opts.sessionId)
32
+ headers[MCP_HEADERS.sessionId] = opts.sessionId;
33
+ if (opts.lastEventId)
34
+ headers[MCP_HEADERS.lastEventId] = opts.lastEventId;
35
+ if (opts.authorization)
36
+ headers['Authorization'] = opts.authorization;
37
+ return headers;
38
+ }
39
+ /**
40
+ * Validate MCP response headers for protocol compliance.
41
+ * Pure - testable.
42
+ */
43
+ export function validateMcpResponseHeaders(headers) {
44
+ const issues = [];
45
+ const version = headers[MCP_HEADERS.protocolVersion];
46
+ if (!version)
47
+ issues.push(`missing ${MCP_HEADERS.protocolVersion} header`);
48
+ else if (!version.startsWith('2026-'))
49
+ issues.push(`unsupported protocol version: ${version}`);
50
+ const sid = headers[MCP_HEADERS.sessionId];
51
+ if (sid)
52
+ return { valid: issues.length === 0, issues, sessionId: sid };
53
+ return { valid: issues.length === 0, issues };
54
+ }
55
+ /**
56
+ * Determine if a tools/resources list response can be cached.
57
+ * The 2026-07-28 spec makes list results cacheable via ETag.
58
+ * Pure - testable.
59
+ */
60
+ export function isCacheableListResponse(headers) {
61
+ const etag = headers['ETag'] || headers['etag'];
62
+ return { cacheable: Boolean(etag), etag };
63
+ }
64
+ /**
65
+ * Build a conditional list request using a cached ETag.
66
+ * Pure - testable.
67
+ */
68
+ export function buildConditionalListRequest(cachedEtag) {
69
+ if (!cachedEtag)
70
+ return {};
71
+ return { 'If-None-Match': cachedEtag };
72
+ }
73
+ /**
74
+ * Check if an HTTP 304 response means the cached list is still valid.
75
+ * Pure - testable.
76
+ */
77
+ export function isNotModified(status) {
78
+ return status === 304;
79
+ }
80
+ /**
81
+ * Task state machine per the Tasks extension.
82
+ * Pure - testable.
83
+ */
84
+ export function canTransitionTask(from, to) {
85
+ const transitions = {
86
+ 'submitted': ['working', 'cancelled', 'failed'],
87
+ 'working': ['input-required', 'completed', 'cancelled', 'failed'],
88
+ 'input-required': ['working', 'cancelled', 'failed'],
89
+ 'completed': [], // terminal
90
+ 'cancelled': [], // terminal
91
+ 'failed': [], // terminal
92
+ };
93
+ return transitions[from]?.includes(to) ?? false;
94
+ }
95
+ /**
96
+ * Authorization check per the 2026-07-28 hardening requirements.
97
+ * Pure - testable.
98
+ */
99
+ export function validateMcpAuth(config) {
100
+ if (config.type === 'stdio') {
101
+ // stdio doesn't need HTTP auth (local process boundary)
102
+ return { authorized: true, reason: 'stdio transport (local trust)' };
103
+ }
104
+ // HTTP transport requires Authorization header
105
+ const auth = config.headers?.['Authorization'];
106
+ if (!auth)
107
+ return { authorized: false, reason: 'HTTP transport requires Authorization header' };
108
+ if (!auth.startsWith('Bearer ') && !auth.startsWith('Basic ')) {
109
+ return { authorized: false, reason: 'Authorization must be Bearer or Basic scheme' };
110
+ }
111
+ return { authorized: true, reason: 'valid authorization scheme' };
112
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/kernel",
3
- "version": "0.9.2",
3
+ "version": "0.9.4",
4
4
  "description": "hmharness kernel: tool registry, provider adapters, the agent loop, session log, config. Zero runtime dependencies (Node >=22 native fetch).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",