osuite 2.10.0 → 2.10.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 +107 -75
- package/activationMetrics.js +116 -0
- package/cli.js +409 -57
- package/credentials.js +234 -0
- package/installationIdentity.js +113 -0
- package/osuite.js +32 -11
- package/package.json +9 -3
- package/projectHooks.js +204 -29
- package/runtime/admission.mjs +209 -0
- package/runtime/config.mjs +58 -0
- package/runtime/context.mjs +122 -0
- package/runtime/cursor.mjs +83 -0
- package/runtime/git.mjs +46 -0
- package/runtime/hook.mjs +202 -0
- package/runtime/mcp.mjs +219 -0
- package/runtime/outcome.mjs +98 -0
- package/runtime/posture.mjs +168 -0
- package/runtime/protocol.mjs +101 -0
- package/runtime/shell.mjs +186 -0
- package/runtime/state.mjs +83 -0
- package/tryContract.js +47 -0
- package/tryFlow.js +90 -0
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { canonicalJson, sha256 } from './protocol.mjs';
|
|
3
|
+
|
|
4
|
+
const basename = token => path.basename(String(token || '')).toLowerCase();
|
|
5
|
+
const set = text => new Set(text.split(' '));
|
|
6
|
+
const shells = set('sh bash zsh dash');
|
|
7
|
+
const gitValueFlags = set('-C -c --git-dir --work-tree --namespace --exec-path --config-env');
|
|
8
|
+
const protectedRef = ref => /^(?:(?:refs\/heads\/)?(?:main|master|prod|production|stable)|(?:refs\/heads\/)?release(?:\/.*)?)$/.test(ref || '');
|
|
9
|
+
|
|
10
|
+
export function parseShell(command) {
|
|
11
|
+
const segments = [], errors = [];
|
|
12
|
+
let current = '', quote = null, started = false, segment = [], operator = null;
|
|
13
|
+
const flush = () => { if (started) { segment.push(current); current = ''; started = false; operator = null; } };
|
|
14
|
+
for (let i = 0; i < command.length; i += 1) {
|
|
15
|
+
const char = command[i];
|
|
16
|
+
if (quote === "'") { if (char === quote) quote = null; else current += char; continue; }
|
|
17
|
+
if (char === '\\') {
|
|
18
|
+
if (i + 1 === command.length) { errors.push('dangling_escape'); break; }
|
|
19
|
+
const next = command[i + 1];
|
|
20
|
+
if (quote === '"' && !'$`"\\\n'.includes(next)) { current += char; continue; }
|
|
21
|
+
i += 1;
|
|
22
|
+
if (next !== '\n') { current += next; started = true; }
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if ('$`'.includes(char)) errors.push('unsupported_expansion');
|
|
26
|
+
if (quote === '"') { if (char === quote) quote = null; else current += char; continue; }
|
|
27
|
+
if ('"\''.includes(char)) { quote = char; started = true; continue; }
|
|
28
|
+
if (char === '#' && !started) { errors.push('unsupported_comment'); while (i < command.length && command[i] !== '\n') i += 1; continue; }
|
|
29
|
+
if (char === '<' && command[i + 1] === '<') { errors.push('unsupported_heredoc'); break; }
|
|
30
|
+
if ('*?['.includes(char)) errors.push('unsupported_glob_expansion');
|
|
31
|
+
if ('<>(){}'.includes(char)) errors.push('unsupported_shell_syntax');
|
|
32
|
+
if (char === '&' && command[i + 1] !== '&') errors.push('unsupported_background');
|
|
33
|
+
const separator = ';|\n'.includes(char) || (char === '&' && command[i + 1] === '&');
|
|
34
|
+
if (separator || /\s/.test(char)) {
|
|
35
|
+
flush();
|
|
36
|
+
if (separator) {
|
|
37
|
+
const nextOperator = (char === '&' || char === '|') && command[i + 1] === char ? char + command[++i] : char;
|
|
38
|
+
if (segment.length) segments.push(segment);
|
|
39
|
+
else if (nextOperator !== '\n') errors.push('empty_segment');
|
|
40
|
+
segment = []; operator = nextOperator;
|
|
41
|
+
}
|
|
42
|
+
} else { current += char; started = true; }
|
|
43
|
+
}
|
|
44
|
+
flush();
|
|
45
|
+
if (segment.length) segments.push(segment);
|
|
46
|
+
if (quote) errors.push('unclosed_quote');
|
|
47
|
+
if (['&&', '||', '|'].includes(operator)) errors.push('missing_operand');
|
|
48
|
+
return { segments, errors: [...new Set(errors)] };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function unwrap(tokens) {
|
|
52
|
+
let argv = [...tokens];
|
|
53
|
+
for (let depth = 0; depth < 8 && argv.length; depth += 1) {
|
|
54
|
+
while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[0] || '')) argv.shift();
|
|
55
|
+
const exe = basename(argv[0]);
|
|
56
|
+
if (set('command builtin noglob').has(exe)) { argv.shift(); while ((argv[0] || '').startsWith('-')) argv.shift(); continue; }
|
|
57
|
+
if (!set('env sudo doas').has(exe)) break;
|
|
58
|
+
argv.shift();
|
|
59
|
+
const valueFlags = exe === 'env' ? set('-u --unset -C --chdir -S --split-string') : set('-u -g -h -p -C -T');
|
|
60
|
+
while (argv.length && (argv[0].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[0]))) {
|
|
61
|
+
const flag = argv.shift();
|
|
62
|
+
// env -S evaluates another argument string; do not guess at its grammar.
|
|
63
|
+
if (flag === '-S' || flag.startsWith('--split-string')) return [];
|
|
64
|
+
if (valueFlags.has(flag)) argv.shift();
|
|
65
|
+
if (flag === '--') break;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return argv;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function result(type, risk, reversible, canonical) {
|
|
72
|
+
return { action_type: type, risk_score: risk, reversible, systems_touched: canonical.systems_touched,
|
|
73
|
+
summary: { tool_name: canonical.executable, tool_category: canonical.tool_category, canonical_action: canonical,
|
|
74
|
+
action_fingerprint: sha256(canonicalJson(canonical)).slice(0, 32), classification_source: 'osuite_shell_semantics',
|
|
75
|
+
classification_status: canonical.classification_status || 'complete' } };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function incomplete(argv, cwd, reasons) {
|
|
79
|
+
return result('review', 40, null, { runtime: 'bash', executable: basename(argv[0]) || 'shell', operation: argv.slice(1).join(' '),
|
|
80
|
+
tool_category: 'other', cwd, systems_touched: ['shell'], classification_status: 'incomplete',
|
|
81
|
+
uncertainty_reasons: reasons, command_commitment: sha256(canonicalJson(argv)).slice(0, 32) });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function boundedObservation(exe, args) {
|
|
85
|
+
const switches = {
|
|
86
|
+
rg: set('--files --hidden --no-ignore --no-ignore-vcs --no-ignore-dot --follow --fixed-strings --ignore-case --case-sensitive --smart-case --line-number --files-with-matches --files-without-match --count --count-matches --only-matching --quiet --word-regexp --line-regexp --no-heading --heading --with-filename --no-filename --text --multiline --pcre2 --stats --sort-files --no-messages'),
|
|
87
|
+
sed: set('-n -E --quiet --silent --regexp-extended'),
|
|
88
|
+
jq: set('-r -c -e -s -n -R -S -M -C --raw-output --compact-output --exit-status --slurp --null-input --raw-input --sort-keys --monochrome-output --color-output'),
|
|
89
|
+
}[exe];
|
|
90
|
+
const values = { rg: set('-g --glob --iglob -e --regexp -t --type -T --type-not --max-count -m --max-depth --encoding --color --context -C --after-context -A --before-context -B'), sed: set('-e --expression'), jq: set('--arg --argjson') }[exe];
|
|
91
|
+
const operands = [], expressions = [];
|
|
92
|
+
let flags = true;
|
|
93
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
94
|
+
const arg = args[i];
|
|
95
|
+
if (arg === '--') { flags = false; continue; }
|
|
96
|
+
if (flags && arg.startsWith('-')) {
|
|
97
|
+
if (switches.has(arg) || (exe === 'rg' && /^-[niFlovqwsSHh]+$/.test(arg))) continue;
|
|
98
|
+
const flag = arg.split('=')[0];
|
|
99
|
+
if (!values.has(flag)) return false;
|
|
100
|
+
const count = exe === 'jq' ? 2 : 1;
|
|
101
|
+
if (arg.includes('=')) { if (exe === 'sed') expressions.push(arg.slice(arg.indexOf('=') + 1)); continue; }
|
|
102
|
+
if (i + count >= args.length) return false;
|
|
103
|
+
if (exe === 'sed') expressions.push(args[i + 1]);
|
|
104
|
+
i += count;
|
|
105
|
+
} else operands.push(arg);
|
|
106
|
+
}
|
|
107
|
+
if (exe === 'sed') {
|
|
108
|
+
if (!expressions.length) expressions.push(operands[0] || '');
|
|
109
|
+
return expressions.every(value => /^(?:(?:[0-9]+(?:,(?:[0-9]+|\$))?|\$))?p$/.test(value));
|
|
110
|
+
}
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function classifyArgv(tokens, cwd, depth) {
|
|
115
|
+
const argv = unwrap(tokens), exe = basename(argv[0]), args = argv.slice(1);
|
|
116
|
+
if (!exe) return incomplete(tokens, cwd, ['unsupported_wrapper']);
|
|
117
|
+
if (shells.has(exe)) {
|
|
118
|
+
const index = args.findIndex(arg => /^-[a-z]*c$/.test(arg));
|
|
119
|
+
return index >= 0 && typeof args[index + 1] === 'string' && depth < 4
|
|
120
|
+
? classifyShell(args[index + 1], cwd, depth + 1) : incomplete(argv, cwd, ['unsupported_shell_invocation']);
|
|
121
|
+
}
|
|
122
|
+
const canonical = { runtime: 'bash', executable: exe, operation: args[0] || '', tool_category: 'other', cwd, systems_touched: [exe] };
|
|
123
|
+
const classified = (type, risk, reversible, category = 'deployment') => result(type, risk, reversible, { ...canonical, tool_category: category });
|
|
124
|
+
if (exe === 'git') {
|
|
125
|
+
let index = 0;
|
|
126
|
+
while (index < args.length && args[index].startsWith('-')) { const flag = args[index++]; if (gitValueFlags.has(flag)) index += 1; }
|
|
127
|
+
const operation = args[index], rest = args.slice(index + 1);
|
|
128
|
+
canonical.operation = operation || '';
|
|
129
|
+
if (set('push merge rebase reset').has(operation)) {
|
|
130
|
+
const positional = rest.filter(value => !value.startsWith('-'));
|
|
131
|
+
canonical.remote = positional[0] || null; canonical.ref = positional[1] || null;
|
|
132
|
+
const destructive = rest.some(arg => ['--force', '--delete', '-f', '-d', '--mirror', '--all'].includes(arg) || arg.startsWith('--force-with-lease') || arg.startsWith(':'));
|
|
133
|
+
return classified('deploy', destructive ? 92 : protectedRef(canonical.ref) ? 80 : 62, false);
|
|
134
|
+
}
|
|
135
|
+
const risks = { status: 10, log: 10, branch: 10, show: 12, remote: 14, diff: 18 };
|
|
136
|
+
// Listing branches/remotes is an observation, but those subcommands can also mutate.
|
|
137
|
+
if ((operation === 'branch' && rest.some(arg => !arg.startsWith('-')) && !rest.includes('--list')) ||
|
|
138
|
+
(operation === 'branch' && rest.some(arg => /^-(?:[dDmMcC]|-delete|-move|-copy)/.test(arg))) ||
|
|
139
|
+
(operation === 'remote' && rest.some(arg => !arg.startsWith('-')))) return incomplete(argv, cwd, ['git_mutation_not_classified']);
|
|
140
|
+
if (risks[operation] !== undefined) return classified('monitor', risks[operation], true, 'observation');
|
|
141
|
+
return incomplete(argv, cwd, ['unsupported_git_operation']);
|
|
142
|
+
}
|
|
143
|
+
if (set('rg sed jq').has(exe)) return boundedObservation(exe, args) ? classified('other', 20, true, 'observation') : incomplete(argv, cwd, ['unbounded_observation']);
|
|
144
|
+
if (exe === 'rm' && args.slice(0, args.indexOf('--') < 0 ? undefined : args.indexOf('--')).some(arg => /^-[rf]+$/.test(arg) && arg.includes('r') && arg.includes('f'))) return classified('security', 90, false);
|
|
145
|
+
if (exe === 'npm' && args[0] === 'run' && args[1] === 'deploy') return classified('deploy', 75, false);
|
|
146
|
+
if ((exe === 'npm' && args[0] === 'run' && args[1] === 'build') || (set('npm pip pip3').has(exe) && args[0] === 'install') || (exe === 'yarn' && args[0] === 'add')) return classified('build', 30, true, 'build');
|
|
147
|
+
if (set('vercel netlify heroku railway fly').has(exe) && args.includes('deploy')) return classified('deploy', 75, false);
|
|
148
|
+
if (exe === 'kubectl') {
|
|
149
|
+
if (set('api-resources api-versions cluster-info describe diff explain get logs top version').has(args[0])) return classified('monitor', 28, true, 'observation');
|
|
150
|
+
if (set('annotate apply autoscale cordon create delete drain edit label patch replace rollout scale set taint uncordon').has(args[0])) return classified('deploy', 85, false);
|
|
151
|
+
return incomplete(argv, cwd, ['unsupported_kubectl_operation']);
|
|
152
|
+
}
|
|
153
|
+
const infra = {
|
|
154
|
+
terraform: [set('fmt graph output plan providers show validate version workspace'), 38, set('apply destroy force-unlock import init state taint untaint'), 90, 78],
|
|
155
|
+
helm: [set('diff get history lint list show status template test version'), 36, set('install rollback uninstall upgrade'), 84, 72],
|
|
156
|
+
pulumi: [set('about preview stack version whoami'), 38, set('cancel destroy import refresh up'), 88, 76],
|
|
157
|
+
}[exe];
|
|
158
|
+
if (infra) return infra[0].has(args[0]) ? classified('review', infra[1], true, 'planning') : classified('deploy', infra[2].has(args[0]) ? infra[3] : infra[4], false);
|
|
159
|
+
if (set('ansible ansible-playbook').has(exe)) return args.some(arg => set('--check --diff -C').has(arg)) ? classified('review', 40, true, 'planning') : classified('deploy', 82, false);
|
|
160
|
+
if (exe === 'az') {
|
|
161
|
+
canonical.raw_operation = args.join(' ');
|
|
162
|
+
if (args[0] === 'keyvault' && args[1] === 'secret') {
|
|
163
|
+
canonical.operation = args.slice(0, 3).join(' '); canonical.systems_touched = ['azure-keyvault'];
|
|
164
|
+
const read = set('backup download list show').has(args[2]);
|
|
165
|
+
return classified('security', read ? 74 : 88, read, 'secret_access');
|
|
166
|
+
}
|
|
167
|
+
if (args[0] === 'role' && args[1] === 'assignment') return classified('security', 86, false, 'access_control');
|
|
168
|
+
// Unresolved Azure resource scope must never be called a complete bounded operation.
|
|
169
|
+
const unknown = incomplete(argv, cwd, ['unresolved_azure_scope']);
|
|
170
|
+
return args.includes('delete') ? { ...unknown, action_type: 'security', risk_score: 90, reversible: false } : unknown;
|
|
171
|
+
}
|
|
172
|
+
return incomplete(argv, cwd, ['unsupported_executable']);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function classifyShell(command, cwd = '', depth = 0) {
|
|
176
|
+
const parsed = parseShell(command);
|
|
177
|
+
const results = parsed.segments.map(argv => classifyArgv(argv, cwd, depth));
|
|
178
|
+
if (parsed.errors.length || !results.length) results.push(incomplete([command], cwd, parsed.errors.length ? parsed.errors : ['empty_command']));
|
|
179
|
+
if (results.length === 1) return results[0];
|
|
180
|
+
const primary = [...results].sort((a, b) => b.risk_score - a.risk_score || Number(b.reversible === false) - Number(a.reversible === false))[0];
|
|
181
|
+
return { ...primary, reversible: results.some(value => value.reversible === false) ? false : results.some(value => value.reversible === null) ? null : true,
|
|
182
|
+
systems_touched: [...new Set(results.flatMap(value => value.systems_touched))],
|
|
183
|
+
summary: { ...primary.summary, canonical_actions: results.map(value => value.summary.canonical_action),
|
|
184
|
+
classification_status: results.some(value => value.summary.classification_status === 'incomplete') ? 'incomplete' : 'complete',
|
|
185
|
+
compound_command_commitment: sha256(command).slice(0, 32) } };
|
|
186
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { canonicalJson, sha256 } from './protocol.mjs';
|
|
6
|
+
|
|
7
|
+
const MAX_STATE_BYTES = 2 * 1024 * 1024;
|
|
8
|
+
|
|
9
|
+
function checkedFile(filename) {
|
|
10
|
+
try {
|
|
11
|
+
const stat = fs.lstatSync(filename);
|
|
12
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) throw new Error('Unsafe runtime state file');
|
|
13
|
+
return stat;
|
|
14
|
+
} catch (error) {
|
|
15
|
+
if (error.code === 'ENOENT') return null;
|
|
16
|
+
throw error;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createStateStore(config) {
|
|
21
|
+
const root = path.resolve(config.stateDir || path.join(os.tmpdir(), `osuite-node-${process.getuid?.() ?? 'user'}`));
|
|
22
|
+
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
23
|
+
const rootStat = fs.lstatSync(root);
|
|
24
|
+
if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error('Unsafe runtime state directory');
|
|
25
|
+
if (process.getuid && (rootStat.uid !== process.getuid() || (rootStat.mode & 0o022))) {
|
|
26
|
+
throw new Error('Runtime state directory is not owner-controlled');
|
|
27
|
+
}
|
|
28
|
+
const scope = sha256(canonicalJson({
|
|
29
|
+
base_url: config.baseUrl || '', credential: sha256(config.apiKey || ''),
|
|
30
|
+
agent_id: config.agentId || '', runtime_id: config.runtimeId || '', provider: config.provider || '',
|
|
31
|
+
}));
|
|
32
|
+
const filename = name => path.join(root, `osuite_${scope.slice(0, 24)}_${sha256(name)}.json`);
|
|
33
|
+
const store = {
|
|
34
|
+
path: filename,
|
|
35
|
+
read(name) {
|
|
36
|
+
const file = filename(name);
|
|
37
|
+
if (!checkedFile(file)) return null;
|
|
38
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | fs.constants.O_NONBLOCK);
|
|
39
|
+
try {
|
|
40
|
+
const stat = fs.fstatSync(fd);
|
|
41
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_STATE_BYTES) throw new Error('Invalid runtime state file');
|
|
42
|
+
return JSON.parse(fs.readFileSync(fd, 'utf8'));
|
|
43
|
+
} finally { fs.closeSync(fd); }
|
|
44
|
+
},
|
|
45
|
+
write(name, value) {
|
|
46
|
+
const file = filename(name);
|
|
47
|
+
checkedFile(file);
|
|
48
|
+
const bytes = JSON.stringify(value);
|
|
49
|
+
if (Buffer.byteLength(bytes) > MAX_STATE_BYTES) throw new Error('Runtime state too large');
|
|
50
|
+
const pending = path.join(root, `.osuite_pending_${randomUUID()}`);
|
|
51
|
+
let fd;
|
|
52
|
+
try {
|
|
53
|
+
fd = fs.openSync(pending, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW || 0), 0o600);
|
|
54
|
+
fs.writeFileSync(fd, bytes);
|
|
55
|
+
fs.fsyncSync(fd);
|
|
56
|
+
fs.closeSync(fd);
|
|
57
|
+
fd = undefined;
|
|
58
|
+
checkedFile(file);
|
|
59
|
+
fs.renameSync(pending, file);
|
|
60
|
+
} finally {
|
|
61
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
62
|
+
try { fs.unlinkSync(pending); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
remove(name) {
|
|
66
|
+
const file = filename(name);
|
|
67
|
+
if (checkedFile(file)) fs.unlinkSync(file);
|
|
68
|
+
},
|
|
69
|
+
update(name, transform) {
|
|
70
|
+
const lock = `${filename(name)}.lock`;
|
|
71
|
+
try { fs.mkdirSync(lock, { mode: 0o700 }); } catch (error) {
|
|
72
|
+
if (error.code === 'EEXIST') throw new Error('Runtime state is busy');
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
const next = transform(store.read(name));
|
|
77
|
+
store.write(name, next);
|
|
78
|
+
return next;
|
|
79
|
+
} finally { fs.rmdirSync(lock); }
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
return store;
|
|
83
|
+
}
|
package/tryContract.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export const TRY_OUTPUT = 'OSuite walkthrough approved. This acknowledgement is the only local effect.';
|
|
2
|
+
const GOAL = 'Print one fixed local acknowledgement after a human review (synthetic walkthrough).';
|
|
3
|
+
const SCOPE = 'One terminal acknowledgement. No files, commands, payments or external services.';
|
|
4
|
+
const TYPE = 'osuite.onboarding_acknowledgement';
|
|
5
|
+
const RUN_ID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
6
|
+
|
|
7
|
+
export function createTryAction({ agentId, runId }) {
|
|
8
|
+
if (!agentId || !RUN_ID.test(runId)) throw new Error('A connected agent and a unique walkthrough ID are required');
|
|
9
|
+
return {
|
|
10
|
+
action_id: `act_try_${runId}`, agent_id: agentId, action_type: TYPE,
|
|
11
|
+
declared_goal: GOAL, authorization_scope: SCOPE, reversible: true,
|
|
12
|
+
systems_touched: ['local_terminal'], status: 'running',
|
|
13
|
+
runtime_session_id: `try_${runId}`, runtime_family: 'sdk_runtime', adapter_mode: 'inline',
|
|
14
|
+
input_summary: JSON.stringify({ walkthrough: { version: 1, run_id: runId, output: TRY_OUTPUT } }),
|
|
15
|
+
provenance_version: 'osuite-prov-v1',
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function isTryAction(action = {}) {
|
|
20
|
+
let trial;
|
|
21
|
+
try { trial = JSON.parse(action.input_summary || '').walkthrough; } catch { return false; }
|
|
22
|
+
let systems = action.systems_touched;
|
|
23
|
+
if (typeof systems === 'string') { try { systems = JSON.parse(systems); } catch { return false; } }
|
|
24
|
+
return action.action_type === TYPE && action.declared_goal === GOAL && action.authorization_scope === SCOPE
|
|
25
|
+
&& (action.reversible === true || action.reversible === 1) && JSON.stringify(systems) === '["local_terminal"]'
|
|
26
|
+
&& trial?.version === 1 && RUN_ID.test(trial.run_id) && trial.output === TRY_OUTPUT
|
|
27
|
+
&& action.action_id === `act_try_${trial.run_id}`
|
|
28
|
+
&& (action.runtime_session_id || action.action_envelope?.runtime_session_id) === `try_${trial.run_id}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Asking for an extra human review is narrowing, never an exception to policy.
|
|
32
|
+
export function narrowTryDecision(previous, action) {
|
|
33
|
+
if (!isTryAction(action) || !['allow', 'warn'].includes(previous?.decision)) return previous;
|
|
34
|
+
const snapshot = previous.policy_snapshot || {};
|
|
35
|
+
return {
|
|
36
|
+
...previous, decision: 'require_approval',
|
|
37
|
+
reason: 'This synthetic walkthrough explicitly requests a human review before its fixed terminal acknowledgement.',
|
|
38
|
+
policy_snapshot: {
|
|
39
|
+
...snapshot, effective_decision: 'require_approval',
|
|
40
|
+
effective_rule_metadata: [
|
|
41
|
+
...(Array.isArray(snapshot.effective_rule_metadata) ? snapshot.effective_rule_metadata : []),
|
|
42
|
+
{ rule_id: 'onboarding:explicit_review', rule_name: 'Synthetic walkthrough: explicit human review',
|
|
43
|
+
rule_type: 'onboarding_review', source: 'onboarding', outcome_action: 'require_approval' },
|
|
44
|
+
],
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
package/tryFlow.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { createTryAction, isTryAction, TRY_OUTPUT } from './tryContract.js';
|
|
3
|
+
|
|
4
|
+
function canonical(value) {
|
|
5
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
|
|
6
|
+
if (value && typeof value === 'object') {
|
|
7
|
+
return `{${Object.keys(value).filter((key) => value[key] !== undefined).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`;
|
|
8
|
+
}
|
|
9
|
+
return JSON.stringify(value ?? null);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function assertApprovedAction(current, proposed, now, { redeemed = false } = {}) {
|
|
13
|
+
if (!current || current.action_id !== proposed.action_id || current.agent_id !== proposed.agent_id || !isTryAction(current)) {
|
|
14
|
+
throw new Error('The returned action does not match the fixed walkthrough binding');
|
|
15
|
+
}
|
|
16
|
+
let votes = current.approval_votes || [];
|
|
17
|
+
try { if (typeof votes === 'string') votes = JSON.parse(votes); } catch { votes = null; }
|
|
18
|
+
if (current.status !== 'running' || current.approval_decision !== 'allow'
|
|
19
|
+
|| typeof current.approved_by !== 'string' || !current.approved_by.trim() || current.approved_by === 'api_key'
|
|
20
|
+
|| !current.approved_at || !Array.isArray(votes)
|
|
21
|
+
|| votes.some(vote => vote?.decision === 'allow' && vote?.actor_id === 'api_key')) {
|
|
22
|
+
throw new Error('No explicit human approval for this walkthrough. Nothing was executed.');
|
|
23
|
+
}
|
|
24
|
+
if (current.timestamp_end || (redeemed ? !Number.isFinite(Date.parse(current.approval_redeemed_at || '')) : current.approval_redeemed_at)) {
|
|
25
|
+
throw new Error('The walkthrough grant is ended, already consumed, or not freshly redeemed. Nothing was executed.');
|
|
26
|
+
}
|
|
27
|
+
const expiry = Date.parse(current.approval_expires_at || '');
|
|
28
|
+
if (!Number.isFinite(expiry) || expiry <= now()) throw new Error('The walkthrough approval is expired or has no verifiable expiry');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function runTryFlow({
|
|
32
|
+
client, emit = (text) => process.stdout.write(`${text}\n`),
|
|
33
|
+
now = () => Date.now(), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
34
|
+
timeoutMs = 300000, intervalMs = 2000, privateKeyBase64 = '', signatureRequired = false,
|
|
35
|
+
} = {}) {
|
|
36
|
+
if (!client) throw new Error('Connect a runtime before starting the walkthrough');
|
|
37
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 900000) throw new Error('Walkthrough timeout must be between 1 and 900000 milliseconds');
|
|
38
|
+
const action = createTryAction({ agentId: client.agentId, runId: crypto.randomUUID() });
|
|
39
|
+
const baseUrl = new URL(client.baseUrl);
|
|
40
|
+
const replayUrl = new URL(`/replay/${encodeURIComponent(action.action_id)}`, baseUrl).href;
|
|
41
|
+
if (client.agentKeyId) action.agent_key_id = client.agentKeyId;
|
|
42
|
+
if (signatureRequired && !privateKeyBase64) throw new Error('Required request signing is not configured. Reconnect this runtime.');
|
|
43
|
+
if (privateKeyBase64) {
|
|
44
|
+
const signer = crypto.createSign('RSA-SHA256');
|
|
45
|
+
signer.update(canonical(action));
|
|
46
|
+
action._signature = signer.sign(Buffer.from(privateKeyBase64, 'base64').toString('utf8'), 'base64');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
emit('Synthetic walkthrough: one fixed terminal acknowledgement, only after a human approves. No shell command or external tool will run.');
|
|
50
|
+
emit(`Review and evidence: ${replayUrl}`);
|
|
51
|
+
const created = await client.createAction(action);
|
|
52
|
+
const initial = created?.action;
|
|
53
|
+
if (!initial || initial.action_id !== action.action_id || initial.agent_id !== action.agent_id
|
|
54
|
+
|| initial.status !== 'pending_approval') {
|
|
55
|
+
throw new Error('The workspace did not open a review for this walkthrough. Nothing was executed; inspect the decision before starting a new run.');
|
|
56
|
+
}
|
|
57
|
+
const started = now();
|
|
58
|
+
while (now() - started < timeoutMs) {
|
|
59
|
+
const { action: current } = await client.getAction(action.action_id);
|
|
60
|
+
if (!current || current.action_id !== action.action_id || current.agent_id !== action.agent_id || !isTryAction(current)) {
|
|
61
|
+
throw new Error('The returned action does not match the fixed walkthrough binding');
|
|
62
|
+
}
|
|
63
|
+
if (current.status === 'pending_approval') { await sleep(intervalMs); continue; }
|
|
64
|
+
assertApprovedAction(current, action, now);
|
|
65
|
+
// GET observes a decision; only the existing POST admission path can
|
|
66
|
+
// re-evaluate policy and atomically consume this exact grant.
|
|
67
|
+
let admission;
|
|
68
|
+
try { admission = await client.createAction(action); } catch {
|
|
69
|
+
throw new Error(`Walkthrough admission is unconfirmed. Nothing was printed; do not retry this grant. Inspect ${replayUrl}`);
|
|
70
|
+
}
|
|
71
|
+
if (admission?.approval?.reused !== true || admission.approval.state !== 'approved') {
|
|
72
|
+
throw new Error('No freshly redeemed approval for the same walkthrough. Nothing was executed.');
|
|
73
|
+
}
|
|
74
|
+
assertApprovedAction(admission.action, action, now, { redeemed: true });
|
|
75
|
+
emit(TRY_OUTPUT);
|
|
76
|
+
try {
|
|
77
|
+
const updated = await client.updateOutcome(action.action_id, {
|
|
78
|
+
status: 'completed', output_summary: TRY_OUTPUT, side_effects: ['Printed one fixed local acknowledgement'],
|
|
79
|
+
artifacts_created: [],
|
|
80
|
+
});
|
|
81
|
+
if (updated?.action?.action_id !== action.action_id || updated?.action?.status !== 'completed') {
|
|
82
|
+
throw new Error('Outcome acknowledgement did not match');
|
|
83
|
+
}
|
|
84
|
+
} catch {
|
|
85
|
+
throw new Error(`The local acknowledgement was printed, but its outcome is unconfirmed. Do not repeat it; check ${replayUrl}`);
|
|
86
|
+
}
|
|
87
|
+
return { actionId: action.action_id, replayUrl, status: 'completed' };
|
|
88
|
+
}
|
|
89
|
+
throw new Error(`Timed out waiting for approval. No acknowledgement was printed. Inspect or deny the existing request at ${replayUrl}; it will expire without execution.`);
|
|
90
|
+
}
|