sdtk-code-kit 0.3.4 → 0.4.2
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.
- package/README.md +13 -1
- package/assets/keys/sdtk-entitlement-public.pem +9 -0
- package/assets/manifest/toolkit-bundle.manifest.json +33 -33
- package/assets/manifest/toolkit-bundle.sha256.txt +8 -8
- package/assets/toolkit/toolkit/AGENTS.md +19 -7
- package/assets/toolkit/toolkit/sdtk-spec.config.json +2 -1
- package/assets/toolkit/toolkit/sdtk-spec.config.profiles.example.json +21 -0
- package/package.json +1 -1
- package/src/commands/help.js +10 -0
- package/src/commands/sleep.js +217 -2
- package/src/lib/agent-team-sleep-execute.js +16 -1
- package/src/lib/agent-team-sleep-session.js +42 -4
- package/src/lib/code-premium-loader.js +394 -0
- package/src/lib/sleep-authorization.js +220 -0
- package/src/lib/sleep-report.js +10 -1
|
@@ -9,6 +9,13 @@ const SESSION_MAX_ITERATIONS = 3;
|
|
|
9
9
|
const SESSION_MAX_COST_USD = 3.00;
|
|
10
10
|
const SESSION_MAX_OUTPUT_TOKENS = 48000;
|
|
11
11
|
const SESSION_WALLCLOCK_TIMEOUT_MS = 30 * 60 * 1000;
|
|
12
|
+
// BK-340: hard engine ceilings for authorization-backed sessions (OQ-3). A
|
|
13
|
+
// sleep-authorization artifact may raise the per-session budgets ABOVE the
|
|
14
|
+
// free-tier defaults but NEVER above these — the ceilings live here, in the
|
|
15
|
+
// engine, so no artifact content can widen them.
|
|
16
|
+
const AUTHORIZED_MAX_ITERATIONS = 10;
|
|
17
|
+
const AUTHORIZED_MAX_COST_USD = 10.00;
|
|
18
|
+
const AUTHORIZED_MAX_TTL_HOURS = 24;
|
|
12
19
|
const SESSION_DOC_TARGET_PATTERNS = Object.freeze([
|
|
13
20
|
"docs/**/*.md",
|
|
14
21
|
"governance/**/*.md",
|
|
@@ -131,6 +138,32 @@ function projectedTokens(projectedNextCall) {
|
|
|
131
138
|
return value;
|
|
132
139
|
}
|
|
133
140
|
|
|
141
|
+
// BK-340: validate optional authorization-backed budgets against the hard
|
|
142
|
+
// engine ceilings. Absent budgets keep today's free-tier defaults untouched.
|
|
143
|
+
function resolveSessionBudgets(budgets) {
|
|
144
|
+
if (budgets === undefined || budgets === null) {
|
|
145
|
+
return { maxIterations: SESSION_MAX_ITERATIONS, maxCostUsd: SESSION_MAX_COST_USD };
|
|
146
|
+
}
|
|
147
|
+
if (typeof budgets !== "object" || Array.isArray(budgets)) {
|
|
148
|
+
throw new ValidationError("FAIL_BUDGET_CEILING: session budgets must be an object when provided.");
|
|
149
|
+
}
|
|
150
|
+
const iterations = budgets.max_iterations === undefined ? SESSION_MAX_ITERATIONS : budgets.max_iterations;
|
|
151
|
+
const costUsd = budgets.max_cost_usd === undefined ? SESSION_MAX_COST_USD : budgets.max_cost_usd;
|
|
152
|
+
if (!Number.isInteger(iterations) || iterations < 1) {
|
|
153
|
+
throw new ValidationError("FAIL_BUDGET_CEILING: budgets.max_iterations must be a positive integer.");
|
|
154
|
+
}
|
|
155
|
+
if (iterations > AUTHORIZED_MAX_ITERATIONS) {
|
|
156
|
+
throw new ValidationError(`FAIL_BUDGET_CEILING: budgets.max_iterations exceeds the engine ceiling (${AUTHORIZED_MAX_ITERATIONS}).`);
|
|
157
|
+
}
|
|
158
|
+
if (!Number.isFinite(costUsd) || costUsd <= 0) {
|
|
159
|
+
throw new ValidationError("FAIL_BUDGET_CEILING: budgets.max_cost_usd must be a positive number.");
|
|
160
|
+
}
|
|
161
|
+
if (costUsd > AUTHORIZED_MAX_COST_USD) {
|
|
162
|
+
throw new ValidationError(`FAIL_BUDGET_CEILING: budgets.max_cost_usd exceeds the engine ceiling ($${AUTHORIZED_MAX_COST_USD.toFixed(2)}).`);
|
|
163
|
+
}
|
|
164
|
+
return { maxIterations: iterations, maxCostUsd: costUsd };
|
|
165
|
+
}
|
|
166
|
+
|
|
134
167
|
function createSleepSession(input) {
|
|
135
168
|
const options = input || {};
|
|
136
169
|
const featureKey = safeSegment(options.featureKey, "feature_key");
|
|
@@ -138,6 +171,7 @@ function createSleepSession(input) {
|
|
|
138
171
|
const now = typeof options.nowMs === "function" ? options.nowMs : () => Date.now();
|
|
139
172
|
const startedAtMs = Number(options.startedAtMs === undefined ? now() : options.startedAtMs);
|
|
140
173
|
const pinnedScope = options.pinnedScope || null;
|
|
174
|
+
const { maxIterations, maxCostUsd } = resolveSessionBudgets(options.budgets);
|
|
141
175
|
let iteration = 0;
|
|
142
176
|
let sessionCostUsd = 0;
|
|
143
177
|
let sessionOutputTokens = 0;
|
|
@@ -171,16 +205,16 @@ function createSleepSession(input) {
|
|
|
171
205
|
if (killed) {
|
|
172
206
|
throw new ValidationError("FAIL_SESSION_KILLED: sleep execute session was killed.");
|
|
173
207
|
}
|
|
174
|
-
if (iteration >=
|
|
175
|
-
throw new ValidationError(`FAIL_SESSION_ITERATION_CAP: max iterations reached (${
|
|
208
|
+
if (iteration >= maxIterations) {
|
|
209
|
+
throw new ValidationError(`FAIL_SESSION_ITERATION_CAP: max iterations reached (${maxIterations}).`);
|
|
176
210
|
}
|
|
177
211
|
if (now() - startedAtMs >= SESSION_WALLCLOCK_TIMEOUT_MS) {
|
|
178
212
|
throw new ValidationError("FAIL_SESSION_WALLCLOCK_CAP: 30-minute session wall-clock exceeded.");
|
|
179
213
|
}
|
|
180
214
|
const nextCost = projectedCost(projectedNextCall);
|
|
181
215
|
const nextTokens = projectedTokens(projectedNextCall);
|
|
182
|
-
if (sessionCostUsd + nextCost >
|
|
183
|
-
throw new ValidationError(
|
|
216
|
+
if (sessionCostUsd + nextCost > maxCostUsd) {
|
|
217
|
+
throw new ValidationError(`FAIL_SESSION_COST_CAP: projected session cost exceeds $${maxCostUsd.toFixed(2)}.`);
|
|
184
218
|
}
|
|
185
219
|
if (sessionOutputTokens + nextTokens > SESSION_MAX_OUTPUT_TOKENS) {
|
|
186
220
|
throw new ValidationError("FAIL_SESSION_TOKEN_CAP: projected session output tokens exceed 48000.");
|
|
@@ -264,6 +298,10 @@ function sessionStopConditionFromError(error) {
|
|
|
264
298
|
module.exports = {
|
|
265
299
|
SESSION_MAX_ITERATIONS,
|
|
266
300
|
SESSION_MAX_COST_USD,
|
|
301
|
+
AUTHORIZED_MAX_ITERATIONS,
|
|
302
|
+
AUTHORIZED_MAX_COST_USD,
|
|
303
|
+
AUTHORIZED_MAX_TTL_HOURS,
|
|
304
|
+
resolveSessionBudgets,
|
|
267
305
|
SESSION_MAX_OUTPUT_TOKENS,
|
|
268
306
|
SESSION_WALLCLOCK_TIMEOUT_MS,
|
|
269
307
|
SESSION_DOC_TARGET_PATTERNS,
|
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// BK-340 — sdtk-code premium loader (the kit's FIRST premium seam).
|
|
4
|
+
//
|
|
5
|
+
// Mirrors the proven sdtk-wiki single-file loader chain byte-for-byte in
|
|
6
|
+
// behavior: signed entitlement manifest (~/.sdtk/entitlements.json, RSA-SHA256
|
|
7
|
+
// over the canonicalized payload, public key bundled or via
|
|
8
|
+
// SDTK_ENTITLEMENT_PUBLIC_KEY) -> capability check -> premium-pack cache
|
|
9
|
+
// verification (~/.sdtk/packs/<product>/<id>/<version>/, sha256 pinned by the
|
|
10
|
+
// signed manifest) -> handler load. Fail-closed at every step: without an
|
|
11
|
+
// active entitlement AND an intact sleep-execute-pro pack, no headless
|
|
12
|
+
// sleep-execution path exists on this machine.
|
|
13
|
+
|
|
14
|
+
const crypto = require("crypto");
|
|
15
|
+
const fs = require("fs");
|
|
16
|
+
const os = require("os");
|
|
17
|
+
const path = require("path");
|
|
18
|
+
|
|
19
|
+
const SAFE_PACK_PART_RE = /^[A-Za-z0-9._-]+$/;
|
|
20
|
+
const REQUIRED_ENTITLEMENT_FIELDS = [
|
|
21
|
+
"schema_version",
|
|
22
|
+
"customer_id",
|
|
23
|
+
"plan",
|
|
24
|
+
"products",
|
|
25
|
+
"capabilities",
|
|
26
|
+
"issued_at",
|
|
27
|
+
"expires_at",
|
|
28
|
+
"offline_grace_until",
|
|
29
|
+
];
|
|
30
|
+
const REQUIRED_PACK_FIELDS = [
|
|
31
|
+
"id",
|
|
32
|
+
"product",
|
|
33
|
+
"version",
|
|
34
|
+
"capabilities",
|
|
35
|
+
"source",
|
|
36
|
+
"sha256",
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
const SLEEP_EXECUTE_CAPABILITY = "code.sleep.execute";
|
|
40
|
+
|
|
41
|
+
function isSafePackPathPart(value) {
|
|
42
|
+
return (
|
|
43
|
+
typeof value === "string" &&
|
|
44
|
+
SAFE_PACK_PART_RE.test(value) &&
|
|
45
|
+
value !== "." &&
|
|
46
|
+
value !== ".."
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function getSuiteRoot() {
|
|
51
|
+
return path.join(os.homedir(), ".sdtk");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function getEntitlementsFile() {
|
|
55
|
+
return path.join(getSuiteRoot(), "entitlements.json");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function getPacksRoot() {
|
|
59
|
+
return path.join(getSuiteRoot(), "packs");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function resolvePublicKey() {
|
|
63
|
+
if (process.env.SDTK_ENTITLEMENT_PUBLIC_KEY) {
|
|
64
|
+
return process.env.SDTK_ENTITLEMENT_PUBLIC_KEY;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const bundledKeyPath = path.join(
|
|
68
|
+
__dirname,
|
|
69
|
+
"..",
|
|
70
|
+
"..",
|
|
71
|
+
"assets",
|
|
72
|
+
"keys",
|
|
73
|
+
"sdtk-entitlement-public.pem"
|
|
74
|
+
);
|
|
75
|
+
if (fs.existsSync(bundledKeyPath)) {
|
|
76
|
+
return fs.readFileSync(bundledKeyPath, "utf8");
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function canonicalize(value) {
|
|
82
|
+
if (Array.isArray(value)) {
|
|
83
|
+
return value.map(canonicalize);
|
|
84
|
+
}
|
|
85
|
+
if (value !== null && typeof value === "object") {
|
|
86
|
+
const sorted = {};
|
|
87
|
+
for (const key of Object.keys(value).sort()) {
|
|
88
|
+
sorted[key] = canonicalize(value[key]);
|
|
89
|
+
}
|
|
90
|
+
return sorted;
|
|
91
|
+
}
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function buildCanonicalPayload(manifest) {
|
|
96
|
+
const { signature: _signature, ...rest } = manifest;
|
|
97
|
+
return Buffer.from(JSON.stringify(canonicalize(rest)), "utf8");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function evaluateManifestObject(manifest, nowMs) {
|
|
101
|
+
if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) {
|
|
102
|
+
return { state: "malformed", manifest: null };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
for (const field of REQUIRED_ENTITLEMENT_FIELDS) {
|
|
106
|
+
if (!(field in manifest)) {
|
|
107
|
+
return { state: "malformed", manifest };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (typeof manifest.schema_version !== "number") {
|
|
112
|
+
return { state: "malformed", manifest };
|
|
113
|
+
}
|
|
114
|
+
if (typeof manifest.customer_id !== "string" || !manifest.customer_id) {
|
|
115
|
+
return { state: "malformed", manifest };
|
|
116
|
+
}
|
|
117
|
+
if (typeof manifest.plan !== "string" || !manifest.plan) {
|
|
118
|
+
return { state: "malformed", manifest };
|
|
119
|
+
}
|
|
120
|
+
if (
|
|
121
|
+
!manifest.products ||
|
|
122
|
+
typeof manifest.products !== "object" ||
|
|
123
|
+
Array.isArray(manifest.products)
|
|
124
|
+
) {
|
|
125
|
+
return { state: "malformed", manifest };
|
|
126
|
+
}
|
|
127
|
+
if (!Array.isArray(manifest.capabilities)) {
|
|
128
|
+
return { state: "malformed", manifest };
|
|
129
|
+
}
|
|
130
|
+
if (
|
|
131
|
+
typeof manifest.issued_at !== "string" ||
|
|
132
|
+
typeof manifest.expires_at !== "string" ||
|
|
133
|
+
typeof manifest.offline_grace_until !== "string"
|
|
134
|
+
) {
|
|
135
|
+
return { state: "malformed", manifest };
|
|
136
|
+
}
|
|
137
|
+
if (
|
|
138
|
+
!("signature" in manifest) ||
|
|
139
|
+
!manifest.signature ||
|
|
140
|
+
typeof manifest.signature !== "string"
|
|
141
|
+
) {
|
|
142
|
+
return { state: "unsigned", manifest };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const publicKeyPem = resolvePublicKey();
|
|
146
|
+
if (!publicKeyPem) {
|
|
147
|
+
return { state: "untrusted-key", manifest };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
let verified = false;
|
|
151
|
+
try {
|
|
152
|
+
const verifier = crypto.createVerify("RSA-SHA256");
|
|
153
|
+
verifier.update(buildCanonicalPayload(manifest));
|
|
154
|
+
verified = verifier.verify(publicKeyPem, Buffer.from(manifest.signature, "base64"));
|
|
155
|
+
} catch (_err) {
|
|
156
|
+
return { state: "invalid-signature", manifest };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (!verified) {
|
|
160
|
+
return { state: "invalid-signature", manifest };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const now = nowMs !== undefined ? nowMs : Date.now();
|
|
164
|
+
const expiresAt = new Date(manifest.expires_at).getTime();
|
|
165
|
+
const graceUntil = new Date(manifest.offline_grace_until).getTime();
|
|
166
|
+
if (Number.isNaN(expiresAt) || Number.isNaN(graceUntil)) {
|
|
167
|
+
return { state: "malformed", manifest };
|
|
168
|
+
}
|
|
169
|
+
if (now < expiresAt) {
|
|
170
|
+
return { state: "active", manifest };
|
|
171
|
+
}
|
|
172
|
+
if (now < graceUntil) {
|
|
173
|
+
return { state: "grace", manifest };
|
|
174
|
+
}
|
|
175
|
+
return { state: "expired", manifest };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function loadEntitlementState() {
|
|
179
|
+
const filePath = getEntitlementsFile();
|
|
180
|
+
if (!fs.existsSync(filePath)) {
|
|
181
|
+
return { state: "missing", manifest: null };
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
return evaluateManifestObject(JSON.parse(fs.readFileSync(filePath, "utf8")));
|
|
185
|
+
} catch (_err) {
|
|
186
|
+
return { state: "malformed", manifest: null };
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function checkCapability(capability, entitlementState) {
|
|
191
|
+
const state = entitlementState && entitlementState.state;
|
|
192
|
+
const manifest = entitlementState && entitlementState.manifest;
|
|
193
|
+
|
|
194
|
+
if (state === "active" || state === "grace") {
|
|
195
|
+
const capabilities = manifest && Array.isArray(manifest.capabilities)
|
|
196
|
+
? manifest.capabilities
|
|
197
|
+
: [];
|
|
198
|
+
if (capabilities.includes(capability)) {
|
|
199
|
+
return { allowed: true };
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
allowed: false,
|
|
203
|
+
exitCode: 1,
|
|
204
|
+
reason: `Capability "${capability}" is not included in the local entitlement.`,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const integrityStates = new Set(["malformed", "unsigned", "untrusted-key", "invalid-signature"]);
|
|
209
|
+
return {
|
|
210
|
+
allowed: false,
|
|
211
|
+
exitCode: integrityStates.has(state) ? 3 : 1,
|
|
212
|
+
reason: `Capability "${capability}" is blocked because local entitlement state is "${state || "missing"}".`,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function computeSha256(bytes) {
|
|
217
|
+
return crypto.createHash("sha256").update(bytes).digest("hex");
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function validatePackMeta(meta) {
|
|
221
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
|
|
222
|
+
return { valid: false, reason: "pack metadata is not an object" };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
for (const field of REQUIRED_PACK_FIELDS) {
|
|
226
|
+
if (!(field in meta)) {
|
|
227
|
+
return { valid: false, reason: `missing required field: ${field}` };
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (!isSafePackPathPart(meta.id)) {
|
|
232
|
+
return { valid: false, reason: "id must be a safe identifier" };
|
|
233
|
+
}
|
|
234
|
+
if (!isSafePackPathPart(meta.product)) {
|
|
235
|
+
return { valid: false, reason: "product must be a safe identifier" };
|
|
236
|
+
}
|
|
237
|
+
if (!isSafePackPathPart(meta.version)) {
|
|
238
|
+
return { valid: false, reason: "version must be a safe identifier" };
|
|
239
|
+
}
|
|
240
|
+
if (!Array.isArray(meta.capabilities)) {
|
|
241
|
+
return { valid: false, reason: "capabilities must be an array" };
|
|
242
|
+
}
|
|
243
|
+
if (
|
|
244
|
+
!meta.source ||
|
|
245
|
+
typeof meta.source !== "object" ||
|
|
246
|
+
Array.isArray(meta.source) ||
|
|
247
|
+
meta.source.type !== "github-content" ||
|
|
248
|
+
typeof meta.source.path !== "string" ||
|
|
249
|
+
!meta.source.path
|
|
250
|
+
) {
|
|
251
|
+
return { valid: false, reason: 'source.type must be "github-content" with a path' };
|
|
252
|
+
}
|
|
253
|
+
if (typeof meta.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(meta.sha256)) {
|
|
254
|
+
return { valid: false, reason: "sha256 must be a 64-character lowercase hex string" };
|
|
255
|
+
}
|
|
256
|
+
return { valid: true };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function getPackDir(packEntry) {
|
|
260
|
+
return path.join(getPacksRoot(), packEntry.product, packEntry.id, packEntry.version);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function getPackFile(packEntry) {
|
|
264
|
+
return path.join(getPackDir(packEntry), "pack.js");
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function resolvePackState(packEntry) {
|
|
268
|
+
const validation = validatePackMeta(packEntry);
|
|
269
|
+
if (!validation.valid) {
|
|
270
|
+
return { state: "malformed", reason: validation.reason };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const packFile = getPackFile(packEntry);
|
|
274
|
+
const metaFile = path.join(getPackDir(packEntry), "pack.json");
|
|
275
|
+
if (!fs.existsSync(packFile) || !fs.existsSync(metaFile)) {
|
|
276
|
+
return {
|
|
277
|
+
state: "missing",
|
|
278
|
+
reason:
|
|
279
|
+
`Premium pack "${packEntry.id}@${packEntry.version}" is not installed for capability ${SLEEP_EXECUTE_CAPABILITY}.`,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
let cachedMeta;
|
|
284
|
+
try {
|
|
285
|
+
cachedMeta = JSON.parse(fs.readFileSync(metaFile, "utf8"));
|
|
286
|
+
} catch (_err) {
|
|
287
|
+
return { state: "malformed", reason: "pack.json could not be parsed" };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (!cachedMeta || cachedMeta.sha256 !== packEntry.sha256) {
|
|
291
|
+
return { state: "stale", reason: "pack.json hash does not match signed manifest" };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
let bytes;
|
|
295
|
+
try {
|
|
296
|
+
bytes = fs.readFileSync(packFile);
|
|
297
|
+
} catch (err) {
|
|
298
|
+
return { state: "malformed", reason: `pack.js could not be read: ${err.message}` };
|
|
299
|
+
}
|
|
300
|
+
if (computeSha256(bytes) !== packEntry.sha256) {
|
|
301
|
+
return { state: "stale", reason: "pack.js hash does not match signed manifest" };
|
|
302
|
+
}
|
|
303
|
+
return { state: "present" };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Capability pre-check only (no pack load) — used by `sleep authorize` so a
|
|
307
|
+
// user without entitlement is told up front instead of after typing the
|
|
308
|
+
// confirmation phrase.
|
|
309
|
+
function checkSleepExecuteCapability() {
|
|
310
|
+
const entitlementState = loadEntitlementState();
|
|
311
|
+
const check = checkCapability(SLEEP_EXECUTE_CAPABILITY, entitlementState);
|
|
312
|
+
if (!check.allowed) {
|
|
313
|
+
return {
|
|
314
|
+
ok: false,
|
|
315
|
+
exitCode: check.exitCode,
|
|
316
|
+
message:
|
|
317
|
+
`${check.reason} Run SDTK activation (sdtk activate --license <KEY>) to install ` +
|
|
318
|
+
`the Sleep Execute Pro runtime.`,
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
return { ok: true, entitlementState };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async function loadSleepExecuteHandler() {
|
|
325
|
+
const capability = SLEEP_EXECUTE_CAPABILITY;
|
|
326
|
+
const preCheck = checkSleepExecuteCapability();
|
|
327
|
+
if (!preCheck.ok) {
|
|
328
|
+
return preCheck;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const manifest = preCheck.entitlementState.manifest;
|
|
332
|
+
const packs = Array.isArray(manifest.premium_packs) ? manifest.premium_packs : [];
|
|
333
|
+
const packEntry = packs.find(
|
|
334
|
+
(pack) =>
|
|
335
|
+
pack &&
|
|
336
|
+
pack.product === "code" &&
|
|
337
|
+
Array.isArray(pack.capabilities) &&
|
|
338
|
+
pack.capabilities.includes(capability)
|
|
339
|
+
);
|
|
340
|
+
if (!packEntry) {
|
|
341
|
+
return {
|
|
342
|
+
ok: false,
|
|
343
|
+
exitCode: 1,
|
|
344
|
+
message:
|
|
345
|
+
`Premium pack providing "${capability}" is not available. Run SDTK activation ` +
|
|
346
|
+
`to install the Sleep Execute Pro runtime.`,
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const packState = resolvePackState(packEntry);
|
|
351
|
+
if (packState.state !== "present") {
|
|
352
|
+
return {
|
|
353
|
+
ok: false,
|
|
354
|
+
exitCode: packState.state === "malformed" ? 3 : 1,
|
|
355
|
+
message:
|
|
356
|
+
`Premium pack for "${capability}" is not ready (${packState.state}). ` +
|
|
357
|
+
(packState.reason || "Refresh the local entitlement/runtime cache."),
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
let packModule;
|
|
362
|
+
try {
|
|
363
|
+
packModule = require(getPackFile(packEntry));
|
|
364
|
+
} catch (err) {
|
|
365
|
+
return {
|
|
366
|
+
ok: false,
|
|
367
|
+
exitCode: 4,
|
|
368
|
+
message: `Failed to load Sleep Execute Pro runtime pack: ${err.message}`,
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const handler = typeof packModule.sleepExecute === "function" ? packModule.sleepExecute : packModule.run;
|
|
373
|
+
if (typeof handler !== "function") {
|
|
374
|
+
return {
|
|
375
|
+
ok: false,
|
|
376
|
+
exitCode: 3,
|
|
377
|
+
message: 'Sleep Execute Pro runtime pack must export "sleepExecute" or "run".',
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return { ok: true, handler, packEntry };
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
module.exports = {
|
|
385
|
+
SLEEP_EXECUTE_CAPABILITY,
|
|
386
|
+
buildCanonicalPayload,
|
|
387
|
+
canonicalize,
|
|
388
|
+
checkCapability,
|
|
389
|
+
checkSleepExecuteCapability,
|
|
390
|
+
evaluateManifestObject,
|
|
391
|
+
loadEntitlementState,
|
|
392
|
+
loadSleepExecuteHandler,
|
|
393
|
+
resolvePackState,
|
|
394
|
+
};
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// BK-340 — sleep-authorization WRITER (attended side).
|
|
4
|
+
//
|
|
5
|
+
// `sdtk-code sleep authorize` moves the human's deliberate consent from the
|
|
6
|
+
// Phase E in-session TTY confirm to a pre-declared artifact created while the
|
|
7
|
+
// operator is still present. The artifact binds — by sha256 — to the exact
|
|
8
|
+
// sleep-plan bytes and the exact pinned agent-team scope it authorizes, carries
|
|
9
|
+
// budget caps validated against the hard engine ceilings, and expires after a
|
|
10
|
+
// bounded TTL. VALIDATION of the artifact at execute time deliberately lives in
|
|
11
|
+
// the Pro pack (see the BK-340 spec §W4): this module only creates it.
|
|
12
|
+
|
|
13
|
+
const crypto = require("crypto");
|
|
14
|
+
const fs = require("fs");
|
|
15
|
+
const path = require("path");
|
|
16
|
+
const { ValidationError } = require("./errors");
|
|
17
|
+
const { loadSleepPlan, gatherReportSignals, projectSleepReport } = require("./sleep-report");
|
|
18
|
+
const { loadExecuteContext } = require("./agent-team-execute");
|
|
19
|
+
const { loadReadiness } = require("./agent-team-readiness");
|
|
20
|
+
const {
|
|
21
|
+
pinScope,
|
|
22
|
+
AUTHORIZED_MAX_ITERATIONS,
|
|
23
|
+
AUTHORIZED_MAX_COST_USD,
|
|
24
|
+
AUTHORIZED_MAX_TTL_HOURS,
|
|
25
|
+
SESSION_MAX_ITERATIONS,
|
|
26
|
+
SESSION_MAX_COST_USD,
|
|
27
|
+
resolveSessionBudgets,
|
|
28
|
+
} = require("./agent-team-sleep-session");
|
|
29
|
+
|
|
30
|
+
const AUTHORIZATION_SCHEMA = "sdtk.sleep-authorization.v1";
|
|
31
|
+
const DEFAULT_TTL_HOURS = 8;
|
|
32
|
+
|
|
33
|
+
function sha256Hex(bytes) {
|
|
34
|
+
return crypto.createHash("sha256").update(bytes).digest("hex");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// BK-340 F2/F3 integrity binding. Every security-relevant field is folded into
|
|
38
|
+
// one digest so a naive single-field edit (budgets 1->9 within ceiling, or
|
|
39
|
+
// expires_at -> 2099) no longer round-trips: the pack recomputes this digest at
|
|
40
|
+
// execute time and fail-closes on any mismatch.
|
|
41
|
+
//
|
|
42
|
+
// NOTE (honest scope, not tamper-PROOF): the artifact carries no client secret,
|
|
43
|
+
// so a determined local forger who understands this canonical form can recompute
|
|
44
|
+
// the digest and craft a valid artifact within the engine ceilings. That residual
|
|
45
|
+
// is accepted and documented — the digest is tamper-EVIDENCE against naive edits
|
|
46
|
+
// and co-resident processes that do not know the format, and the engine envelope
|
|
47
|
+
// (doc-class guard, hard ceilings, per-iteration readiness re-check, pinned scope,
|
|
48
|
+
// worktree isolation) bounds the blast radius regardless. The pack keeps a
|
|
49
|
+
// byte-identical copy of this function; `test_sdtk_code_sleep_execute_pro.py`
|
|
50
|
+
// asserts the two agree so they cannot drift.
|
|
51
|
+
function authorizationDigestPayload(auth) {
|
|
52
|
+
const a = auth || {};
|
|
53
|
+
const b = a.budgets || {};
|
|
54
|
+
return JSON.stringify([
|
|
55
|
+
AUTHORIZATION_SCHEMA,
|
|
56
|
+
a.feature_key,
|
|
57
|
+
a.plan_sha256,
|
|
58
|
+
a.pinned_scope_sha256,
|
|
59
|
+
b.max_iterations,
|
|
60
|
+
b.max_cost_usd,
|
|
61
|
+
a.patch_class,
|
|
62
|
+
a.created_at,
|
|
63
|
+
a.expires_at,
|
|
64
|
+
]);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function computeAuthorizationDigest(auth) {
|
|
68
|
+
return sha256Hex(Buffer.from(authorizationDigestPayload(auth), "utf8"));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function authorizationPath(projectPath) {
|
|
72
|
+
return path.join(path.resolve(projectPath || "."), ".sdtk", "trust", "sleep-authorization.json");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function sleepPlanPath(projectPath) {
|
|
76
|
+
return path.join(path.resolve(projectPath || "."), ".sdtk", "trust", "sleep-plan.json");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function buildAuthorizationPhrase(featureKey, budgets, ttlHours) {
|
|
80
|
+
return (
|
|
81
|
+
`AUTHORIZE ${featureKey} max_iterations=${budgets.maxIterations} ` +
|
|
82
|
+
`cost_cap=$${budgets.maxCostUsd.toFixed(2)} ttl_hours=${ttlHours} unit=Path2-author-only`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function resolveTtlHours(value) {
|
|
87
|
+
const ttl = value === undefined ? DEFAULT_TTL_HOURS : Number(value);
|
|
88
|
+
if (!Number.isFinite(ttl) || ttl <= 0) {
|
|
89
|
+
throw new ValidationError("SLEEP_AUTH_TTL_INVALID: --ttl-hours must be a positive number.");
|
|
90
|
+
}
|
|
91
|
+
if (ttl > AUTHORIZED_MAX_TTL_HOURS) {
|
|
92
|
+
throw new ValidationError(
|
|
93
|
+
`SLEEP_AUTH_TTL_INVALID: --ttl-hours exceeds the engine ceiling (${AUTHORIZED_MAX_TTL_HOURS}h).`
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
return ttl;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// The attended typed confirmation. Mirrors the Phase E confirm contract:
|
|
100
|
+
// requires a real TTY and the exact phrase — no --yes path exists.
|
|
101
|
+
async function confirmAuthorization(input, phrase) {
|
|
102
|
+
const source = input || {};
|
|
103
|
+
if (source.isTTY !== true) {
|
|
104
|
+
throw new ValidationError(
|
|
105
|
+
"SLEEP_AUTH_REQUIRES_TTY: sleep authorize requires an interactive TTY confirmation."
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
if (typeof source.readLine !== "function") {
|
|
109
|
+
throw new ValidationError("SLEEP_AUTH_REQUIRES_TTY: confirmation reader is not available.");
|
|
110
|
+
}
|
|
111
|
+
const answer = await source.readLine(`Type ${phrase} to authorize: `);
|
|
112
|
+
if (String(answer || "") !== phrase) {
|
|
113
|
+
throw new ValidationError(
|
|
114
|
+
"SLEEP_AUTH_CONFIRMATION_MISMATCH: exact sleep-authorize confirmation phrase was not provided."
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
return { confirmed: true };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Create the sleep-authorization artifact (attended).
|
|
122
|
+
*
|
|
123
|
+
* Preconditions (each fail-closed with a typed error):
|
|
124
|
+
* 1. sleep plan exists and matches the feature key;
|
|
125
|
+
* 2. a FRESH sleep report computes READY_TO_SLEEP;
|
|
126
|
+
* 3. the agent-team execute context loads and its scope pins (bounded);
|
|
127
|
+
* 4. the agent-team readiness artifact is READY_TO_SLEEP;
|
|
128
|
+
* 5. budgets/TTL are within the hard engine ceilings;
|
|
129
|
+
* 6. the operator types the exact confirmation phrase on a TTY.
|
|
130
|
+
*/
|
|
131
|
+
async function createSleepAuthorization(projectPath, featureKey, opts) {
|
|
132
|
+
const options = opts || {};
|
|
133
|
+
const resolved = path.resolve(projectPath || ".");
|
|
134
|
+
|
|
135
|
+
// 1. Sleep plan (throws NEEDS_PLAN when absent) + feature match.
|
|
136
|
+
const plan = loadSleepPlan(resolved);
|
|
137
|
+
if (plan.feature_key !== featureKey) {
|
|
138
|
+
throw new ValidationError(
|
|
139
|
+
`SLEEP_AUTH_PLAN_MISMATCH: sleep-plan feature_key "${plan.feature_key}" does not match --feature-key "${featureKey}".`
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// 2. Fresh sleep-report verdict must be READY_TO_SLEEP.
|
|
144
|
+
const signals = gatherReportSignals(resolved, featureKey);
|
|
145
|
+
const report = projectSleepReport(plan, signals);
|
|
146
|
+
if (report.verdict !== "READY_TO_SLEEP") {
|
|
147
|
+
throw new ValidationError(
|
|
148
|
+
`SLEEP_AUTH_NOT_READY: sleep report verdict is "${report.verdict}" — ${report.reason}`
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// 3. Agent-team execute context + pinned scope (pinScope enforces bounded,
|
|
153
|
+
// non-whole-repo allowed_file_scopes and an allowlisted verification set).
|
|
154
|
+
const ctx = loadExecuteContext(resolved, featureKey);
|
|
155
|
+
const pinnedScope = pinScope(ctx);
|
|
156
|
+
|
|
157
|
+
// 4. Agent-team readiness gate (the engine re-asserts authenticity per
|
|
158
|
+
// iteration; authorize checks the verdict up front for honest UX).
|
|
159
|
+
const readiness = loadReadiness(resolved, featureKey);
|
|
160
|
+
if (!readiness || readiness.overall_verdict !== "READY_TO_SLEEP") {
|
|
161
|
+
throw new ValidationError(
|
|
162
|
+
`SLEEP_AUTH_NOT_READY: agent-team readiness verdict is "${readiness ? readiness.overall_verdict : "absent"}".`
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// 5. Budgets + TTL within engine ceilings (resolveSessionBudgets throws
|
|
167
|
+
// FAIL_BUDGET_CEILING above the hard caps).
|
|
168
|
+
const budgets = resolveSessionBudgets({
|
|
169
|
+
max_iterations: options.maxIterations === undefined ? SESSION_MAX_ITERATIONS : Number(options.maxIterations),
|
|
170
|
+
max_cost_usd: options.maxCostUsd === undefined ? SESSION_MAX_COST_USD : Number(options.maxCostUsd),
|
|
171
|
+
});
|
|
172
|
+
const ttlHours = resolveTtlHours(options.ttlHours);
|
|
173
|
+
|
|
174
|
+
// 6. Attended typed confirmation.
|
|
175
|
+
const phrase = buildAuthorizationPhrase(featureKey, budgets, ttlHours);
|
|
176
|
+
await confirmAuthorization(options.confirmInput || {}, phrase);
|
|
177
|
+
|
|
178
|
+
const planBytes = fs.readFileSync(sleepPlanPath(resolved));
|
|
179
|
+
const nowMs = typeof options.nowMs === "function" ? options.nowMs() : Date.now();
|
|
180
|
+
const createdAt = new Date(nowMs);
|
|
181
|
+
const expiresAt = new Date(nowMs + ttlHours * 60 * 60 * 1000);
|
|
182
|
+
|
|
183
|
+
const authorization = {
|
|
184
|
+
schema_version: AUTHORIZATION_SCHEMA,
|
|
185
|
+
feature_key: featureKey,
|
|
186
|
+
plan_sha256: sha256Hex(planBytes),
|
|
187
|
+
pinned_scope_sha256: sha256Hex(Buffer.from(JSON.stringify(pinnedScope), "utf8")),
|
|
188
|
+
budgets: {
|
|
189
|
+
max_iterations: budgets.maxIterations,
|
|
190
|
+
max_cost_usd: budgets.maxCostUsd,
|
|
191
|
+
},
|
|
192
|
+
patch_class: "doc",
|
|
193
|
+
created_at: createdAt.toISOString(),
|
|
194
|
+
expires_at: expiresAt.toISOString(),
|
|
195
|
+
confirmation: {
|
|
196
|
+
phrase_sha256: sha256Hex(Buffer.from(phrase, "utf8")),
|
|
197
|
+
confirmed_at: createdAt.toISOString(),
|
|
198
|
+
tty: true,
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
// Bind all security-relevant fields (F2/F3). Computed last, over the fields above.
|
|
202
|
+
authorization.authorization_sha256 = computeAuthorizationDigest(authorization);
|
|
203
|
+
|
|
204
|
+
const outPath = authorizationPath(resolved);
|
|
205
|
+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
206
|
+
const tmpPath = `${outPath}.tmp`;
|
|
207
|
+
fs.writeFileSync(tmpPath, JSON.stringify(authorization, null, 2), "utf8");
|
|
208
|
+
fs.renameSync(tmpPath, outPath);
|
|
209
|
+
return { outPath, authorization };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
module.exports = {
|
|
213
|
+
AUTHORIZATION_SCHEMA,
|
|
214
|
+
DEFAULT_TTL_HOURS,
|
|
215
|
+
authorizationPath,
|
|
216
|
+
buildAuthorizationPhrase,
|
|
217
|
+
authorizationDigestPayload,
|
|
218
|
+
computeAuthorizationDigest,
|
|
219
|
+
createSleepAuthorization,
|
|
220
|
+
};
|