@remoteshell/device 0.1.0-beta.1 → 0.1.0-beta.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 (85) hide show
  1. package/LICENSE +26 -0
  2. package/NOTICE +20 -0
  3. package/bin/dev-agent-client.mjs +228 -0
  4. package/bin/dev-agent-runner.mjs +60 -0
  5. package/bin/dev-api-client.mjs +31 -0
  6. package/bin/dev-auto-worker.mjs +25 -0
  7. package/bin/dev-browser-open.mjs +12 -0
  8. package/bin/dev-dogfood-read.mjs +3 -0
  9. package/bin/dev-heartbeat-service.mjs +77 -0
  10. package/bin/dev-pairing-client.mjs +63 -0
  11. package/bin/dev-secrets.mjs +33 -0
  12. package/bin/dev-setup-recovery.mjs +34 -0
  13. package/bin/dev-signer-pin.mjs +22 -0
  14. package/bin/device.mjs +233 -9
  15. package/bin/install-acquire.mjs +89 -0
  16. package/bin/install-integrity.mjs +74 -0
  17. package/bin/install-plan.mjs +43 -0
  18. package/bin/native-path-contract.mjs +23 -0
  19. package/bin/remoteshell-device-install.cmd +17 -0
  20. package/bin/remoteshell-device-install.ps1 +17 -0
  21. package/bin/remoteshell-device-install.sh +15 -0
  22. package/bin/remoteshell-device-preflight.cmd +10 -0
  23. package/bin/remoteshell-device-preflight.ps1 +10 -0
  24. package/bin/remoteshell-easy-diagnose.ps1 +32 -0
  25. package/bin/remoteshell-easy-install.ps1 +289 -0
  26. package/bin/remoteshell-easy-install.sh +71 -0
  27. package/bin/remoteshell-easy-uninstall.ps1 +124 -0
  28. package/bin/windows-credential-boundary.mjs +106 -0
  29. package/bin/windows-install-layout.mjs +28 -0
  30. package/bin/windows-native-installer.mjs +91 -0
  31. package/bin/windows-private-store.mjs +163 -0
  32. package/bin/windows-user-lifecycle.mjs +34 -0
  33. package/npm-shrinkwrap.json +8591 -0
  34. package/package.json +14 -5
  35. package/shared/lib/bounded-search-contract.mjs +5 -0
  36. package/shared/lib/dc-generic-policy.mjs +102 -0
  37. package/shared/lib/dc-relay-contract.mjs +42 -0
  38. package/shared/lib/dc-tool-catalog.mjs +67 -0
  39. package/shared/lib/dev-dc-relay-contract.mjs +20 -0
  40. package/shared/lib/dev-paged-output.mjs +32 -0
  41. package/shared/lib/dev-root-exclusions.mjs +56 -0
  42. package/{src/common → shared/lib}/synthetic-write-policy.mjs +0 -1
  43. package/src/config/l2-dev-oci-credential.mjs +39 -0
  44. package/src/config/p2-private-credential.mjs +15 -0
  45. package/src/connection/dev-dogfood-processes.mjs +25 -0
  46. package/src/connection/dev-dogfood-read.mjs +64 -0
  47. package/src/connection/dev-dogfood-task.mjs +113 -0
  48. package/src/connection/dev-dogfood-write.mjs +62 -0
  49. package/src/connection/dev-file-task.mjs +119 -0
  50. package/src/connection/dev-r4-file-task.mjs +56 -0
  51. package/src/connection/dev-read-tools.mjs +134 -0
  52. package/src/connection/dev-root-scopes.mjs +82 -0
  53. package/src/{device-agent → core}/c1-supervisor.mjs +9 -7
  54. package/src/{device-agent → core}/c1-worker.mjs +7 -7
  55. package/src/dc/dc-access-readiness.mjs +31 -0
  56. package/src/dc/dev-dc-relay.mjs +47 -0
  57. package/src/device-agent/main.mjs +1 -230
  58. package/src/gateway-keepalive.mjs +73 -0
  59. package/src/main.mjs +434 -0
  60. package/src/{common → policy}/bounded-search-adapter.mjs +2 -3
  61. package/src/{common → policy}/isolated-read-adapter.mjs +1 -1
  62. package/src/{common → policy}/isolated-read-mount.mjs +1 -1
  63. package/src/{common → policy}/synthetic-auxiliary-adapter.mjs +1 -1
  64. package/src/{common → policy}/synthetic-file-adapter.mjs +1 -1
  65. package/src/{common → policy}/synthetic-file-transaction.mjs +1 -1
  66. package/src/{common → policy}/synthetic-write-adapter.mjs +2 -3
  67. /package/{src/common → shared/lib}/bounded-search-policy.mjs +0 -0
  68. /package/{src/common → shared/lib}/config.mjs +0 -0
  69. /package/{src/common → shared/lib}/contracts.mjs +0 -0
  70. /package/{src/common → shared/lib}/errors.mjs +0 -0
  71. /package/{src/common → shared/lib}/events.mjs +0 -0
  72. /package/{src/common → shared/lib}/execution-policy.mjs +0 -0
  73. /package/{src/common → shared/lib}/isolated-read-boundary.mjs +0 -0
  74. /package/{src/common → shared/lib}/isolated-read-policy.mjs +0 -0
  75. /package/{src/common → shared/lib}/lifecycle-events.mjs +0 -0
  76. /package/{src/common → shared/lib}/runtime-timing.mjs +0 -0
  77. /package/{src/common → shared/lib}/synthetic-auxiliary-policy.mjs +0 -0
  78. /package/{src/common → shared/lib}/tool-registry.mjs +0 -0
  79. /package/src/{device-agent → core}/c1-dc-transport.mjs +0 -0
  80. /package/src/{device-agent → core}/c1-startup.mjs +0 -0
  81. /package/src/{device-agent → core}/fixture.txt +0 -0
  82. /package/src/{common → policy}/synthetic-write-mount.mjs +0 -0
  83. /package/src/{common → policy}/verified-bounded-search.mjs +0 -0
  84. /package/src/{common → policy}/verified-isolated-read.mjs +0 -0
  85. /package/src/{common → policy}/verified-synthetic-write.mjs +0 -0
package/package.json CHANGED
@@ -1,20 +1,29 @@
1
1
  {
2
2
  "name": "@remoteshell/device",
3
- "version": "0.1.0-beta.1",
4
- "description": "RemoteShell device agent private test package; distribution not enabled",
3
+ "version": "0.1.0-beta.3",
4
+ "description": "RemoteShell public beta device agent",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "remoteshell-device": "./bin/device.mjs"
8
8
  },
9
9
  "files": [
10
10
  "bin/",
11
- "src/"
11
+ "src/",
12
+ "shared/",
13
+ "npm-shrinkwrap.json",
14
+ "LICENSE",
15
+ "NOTICE"
12
16
  ],
13
17
  "engines": {
14
18
  "node": ">=22"
15
19
  },
16
20
  "dependencies": {
17
21
  "@modelcontextprotocol/sdk": "1.32.1",
18
- "@wonderwhy-er/desktop-commander": "0.3.0"
19
- }
22
+ "@wonderwhy-er/desktop-commander": "0.3.1"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/lkhkhk/RemoteShell.git"
27
+ },
28
+ "license": "SEE LICENSE IN LICENSE"
20
29
  }
@@ -0,0 +1,5 @@
1
+ export const BOUNDED_SEARCH_LIMITS=Object.freeze({
2
+ maxSessions:2,maxDepth:3,maxEntries:128,maxFileBytes:65536,maxTreeBytes:4*1024*1024,
3
+ maxPatternBytes:256,maxFilePatternBytes:128,maxResults:200,maxPage:50,maxPathBytes:256,
4
+ maxSnippetBytes:256,maxPageBytes:32768,maxSessionBytes:131072,searchTimeoutMs:30000
5
+ });
@@ -0,0 +1,102 @@
1
+ import {realpathSync,existsSync} from 'node:fs';
2
+ import {resolve,relative,dirname,isAbsolute,sep} from 'node:path';
3
+
4
+ export const DC_PROVIDER_ONLY='give_feedback_to_desktop_commander';
5
+ export const DC_USER_TOOLS=Object.freeze([
6
+ 'get_config','set_config_value','read_file','read_multiple_files','write_file','write_pdf',
7
+ 'create_directory','list_directory','move_file','start_search','get_more_search_results',
8
+ 'stop_search','list_searches','get_file_info','edit_block','start_process',
9
+ 'read_process_output','interact_with_process','force_terminate','list_sessions',
10
+ 'list_processes','kill_process','get_usage_stats','get_recent_tool_calls'
11
+ ]);
12
+ const names=new Set(DC_USER_TOOLS);
13
+ const readNames=new Set(['get_config','read_file','read_multiple_files','list_directory',
14
+ 'start_search','get_more_search_results','list_searches','get_file_info',
15
+ 'read_process_output','list_sessions','list_processes','get_usage_stats','get_recent_tool_calls']);
16
+ const pathNames=new Set(['read_file','read_multiple_files','write_file','write_pdf',
17
+ 'create_directory','list_directory','move_file','start_search','get_file_info','edit_block']);
18
+ const plain=x=>x!==null&&typeof x==='object'&&!Array.isArray(x)&&Object.getPrototypeOf(x)===Object.prototype;
19
+ const deny=()=>{throw Error('DC_GENERIC_DENIED')};
20
+ export const isDcPublic=name=>names.has(name);
21
+ export const dcIsReadonly=name=>readNames.has(name);
22
+ export const dcHasPath=name=>pathNames.has(name);
23
+ export const dcPermissionBase=name=>readNames.has(name)?'read_file':name==='start_process'?'start_process':name;
24
+ // A user-owned Root grants its existing read permission to comparable read tools.
25
+ // All non-read tools must be explicitly granted by the current Root policy.
26
+ export function dcRootToolAllowed(name,allowedTools){
27
+ if(!isDcPublic(name)||!Array.isArray(allowedTools))return false;
28
+ return allowedTools.includes(name)||(readNames.has(name)&&allowedTools.includes('read_file'));
29
+ }
30
+ function schemaCheck(schema,value,level=0){
31
+ if(level>12||!plain(schema))return false;
32
+ if(schema.anyOf)return Array.isArray(schema.anyOf)&&schema.anyOf.some(x=>schemaCheck(x,value,level+1));
33
+ if(schema.oneOf)return Array.isArray(schema.oneOf)&&schema.oneOf.filter(x=>schemaCheck(x,value,level+1)).length===1;
34
+ if(Object.hasOwn(schema,'const')&&JSON.stringify(value)!==JSON.stringify(schema.const))return false;
35
+ if(schema.enum&&!schema.enum.some(x=>JSON.stringify(x)===JSON.stringify(value)))return false;
36
+ const types=Array.isArray(schema.type)?schema.type:[schema.type];
37
+ if(types[0]&& !types.some(t=>t==='object'?plain(value):
38
+ t==='array'?Array.isArray(value):t==='integer'?Number.isSafeInteger(value):
39
+ t==='number'?typeof value==='number'&&Number.isFinite(value):
40
+ t==='string'?typeof value==='string':
41
+ t==='boolean'?typeof value==='boolean':t==='null'?value===null:false))return false;
42
+ if(typeof value==='string'){
43
+ if(value.length>32768||schema.maxLength!==undefined&&value.length>schema.maxLength||
44
+ schema.minLength!==undefined&&value.length<schema.minLength)return false;
45
+ if(schema.pattern){try{if(!new RegExp(schema.pattern).test(value))return false}catch{return false}}
46
+ }
47
+ if(typeof value==='number'){
48
+ if(schema.minimum!==undefined&&value<schema.minimum||
49
+ schema.maximum!==undefined&&value>schema.maximum)return false;
50
+ }
51
+ if(Array.isArray(value)){
52
+ if(value.length>256||schema.maxItems!==undefined&&value.length>schema.maxItems||
53
+ schema.minItems!==undefined&&value.length<schema.minItems)return false;
54
+ if(schema.items&&!value.every(x=>schemaCheck(schema.items,x,level+1)))return false;
55
+ }
56
+ if(plain(value)){
57
+ if(Object.keys(value).length>64)return false;
58
+ const properties=schema.properties||{},required=schema.required||[];
59
+ if(!Array.isArray(required)||!required.every(k=>Object.hasOwn(value,k)))return false;
60
+ for(const [key,item] of Object.entries(value)){
61
+ if(['__proto__','constructor','prototype'].includes(key))return false;
62
+ if(Object.hasOwn(properties,key)){if(!schemaCheck(properties[key],item,level+1))return false}
63
+ else if(!Object.hasOwn(schema,'additionalProperties')||schema.additionalProperties===false)return false;
64
+ else if(plain(schema.additionalProperties)&&!schemaCheck(schema.additionalProperties,item,level+1))return false;
65
+ }
66
+ }
67
+ return true;
68
+ }
69
+ export function validateDcGenericArgs(name,args,catalog){
70
+ if(!isDcPublic(name)||!plain(args)||JSON.stringify(args).length>32768||!Array.isArray(catalog))deny();
71
+ const tool=catalog.find(t=>t.name===name);
72
+ if(!tool||!plain(tool.inputSchema)||!schemaCheck(tool.inputSchema,args))deny();
73
+ return args;
74
+ }
75
+ export function parseDcGenericMcpArgs(name,input,catalog){
76
+ if(!plain(input)||typeof input.device_id!=='string'||
77
+ Object.hasOwn(input,'root_id')||
78
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(input.device_id))deny();
79
+ const {device_id,...args}=input;
80
+ validateDcGenericArgs(name,args,catalog);
81
+ return {deviceId:device_id,name,args};
82
+ }
83
+ export function dcFilePaths(name,args){
84
+ if(!dcHasPath(name))return [];
85
+ if(name==='read_multiple_files')return args.paths||[];
86
+ if(name==='move_file')return [args.source,args.destination];
87
+ if(name==='edit_block')return args.file_path===undefined?[]:[args.file_path];
88
+ if(name==='write_pdf')return [args.path,...(typeof args.outputPath==='string'?[args.outputPath]:[]),...(Array.isArray(args.content)?args.content.filter(x=>x&&typeof x.sourcePdfPath==='string').map(x=>x.sourcePdfPath):[])];
89
+ return args.path===undefined?[]:[args.path];
90
+ }
91
+ export function validateDcPathScope(name,args,root,{requireExisting=false}={}){
92
+ const base=realpathSync(root);
93
+ for(const path of dcFilePaths(name,args)){
94
+ if(typeof path!=='string'||path.length>4096||!isAbsolute(path))deny();
95
+ const full=resolve(path),present=existsSync(full),target=present?realpathSync(full):
96
+ (requireExisting?deny():resolve(realpathSync(dirname(full)),full.split(sep).at(-1)));
97
+ const rel=relative(base,target);
98
+ if(rel==='..'||rel.startsWith('..'+sep)||isAbsolute(rel))deny();
99
+ }
100
+ if(dcHasPath(name)&&dcFilePaths(name,args).length===0)deny();
101
+ return true;
102
+ }
@@ -0,0 +1,42 @@
1
+ import {isAbsolute} from 'node:path';
2
+
3
+ const DENIED=()=>Object.assign(new Error('DC_RELAY_DENIED'),{code:'DC_RELAY_DENIED'});
4
+ const plain=x=>x&&typeof x==='object'&&!Array.isArray(x)&&Object.getPrototypeOf(x)===Object.prototype;
5
+ const schemas={
6
+ read_file:{required:['path'],optional:['isUrl','offset','length','sheet','range','options','origin']},
7
+ list_directory:{required:['path'],optional:['depth','origin']},
8
+ start_process:{required:['command','timeout_ms'],optional:['shell','verbose_timing','origin']},
9
+ read_process_output:{required:['pid'],optional:['timeout_ms','offset','length','verbose_timing']}
10
+ };
11
+ const keys=(o,required,optional)=>plain(o)&&required.every(k=>Object.hasOwn(o,k))&&
12
+ Object.keys(o).every(k=>required.includes(k)||optional.includes(k));
13
+ const nonnegative=n=>Number.isSafeInteger(n)&&n>=0;
14
+
15
+ // Shared argument contract. Only Device Agent invokes the original DC MCP tool.
16
+ export function validateDcRelayArgs(name,args){
17
+ const schema=schemas[name];
18
+ if(!schema||!keys(args,schema.required,schema.optional))throw DENIED();
19
+ if(name==='read_file'){
20
+ if(typeof args.path!=='string'||!isAbsolute(args.path)||args.path.length>4096||
21
+ args.isUrl!==undefined&&args.isUrl!==false||
22
+ args.offset!==undefined&&!nonnegative(args.offset)||
23
+ args.length!==undefined&&(!nonnegative(args.length)||args.length>10000)||
24
+ args.sheet!==undefined&&typeof args.sheet!=='string'||
25
+ args.range!==undefined&&typeof args.range!=='string'||
26
+ args.options!==undefined&&!plain(args.options))throw DENIED();
27
+ }else if(name==='list_directory'){
28
+ if(typeof args.path!=='string'||!isAbsolute(args.path)||args.path.length>4096||
29
+ args.depth!==undefined&&(!Number.isSafeInteger(args.depth)||args.depth<1||args.depth>5))throw DENIED();
30
+ }else if(name==='start_process'){
31
+ if(typeof args.command!=='string'||!args.command.trim()||args.command.length>32768||
32
+ /[\x00-\x08\x0b-\x1f\x7f]/.test(args.command)||
33
+ !Number.isSafeInteger(args.timeout_ms)||args.timeout_ms<1||args.timeout_ms>120000||
34
+ args.shell!==undefined&&typeof args.shell!=='string')throw DENIED();
35
+ }else if(!Number.isSafeInteger(args.pid)||args.pid<=0||
36
+ args.timeout_ms!==undefined&&(!nonnegative(args.timeout_ms)||args.timeout_ms>120000)||
37
+ args.offset!==undefined&&!nonnegative(args.offset)||
38
+ args.length!==undefined&&(!nonnegative(args.length)||args.length>10000))throw DENIED();
39
+ if(args.verbose_timing!==undefined&&typeof args.verbose_timing!=='boolean'||
40
+ args.origin!==undefined&&!['ui','llm'].includes(args.origin))throw DENIED();
41
+ return args;
42
+ }
@@ -0,0 +1,67 @@
1
+ import {createHash} from 'node:crypto';
2
+
3
+ const MAX_TOOLS=128;
4
+ const MAX_PAGES=16;
5
+ const validName=name=>typeof name==='string'&&/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(name);
6
+ const record=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
7
+ function ordered(value){
8
+ if(Array.isArray(value))return value.map(ordered);
9
+ if(record(value))return Object.fromEntries(Object.keys(value).sort().map(k=>[k,ordered(value[k])]));
10
+ return value;
11
+ }
12
+ const stable=value=>JSON.stringify(ordered(value));
13
+ export function normalizeDcCatalog(tools){
14
+ if(!Array.isArray(tools)||tools.length>MAX_TOOLS)throw Error('DC_CATALOG_INVALID');
15
+ const names=new Set();
16
+ return Object.freeze(tools.map(tool=>{
17
+ if(!record(tool)||!validName(tool.name)||names.has(tool.name)||
18
+ typeof tool.description!=='string'||!record(tool.inputSchema)||
19
+ tool.inputSchema.type!=='object'||!record(tool.inputSchema.properties)||
20
+ tool.annotations!==undefined&&!record(tool.annotations))throw Error('DC_CATALOG_INVALID');
21
+ names.add(tool.name);
22
+ // The original DC definitions are authoritative. Do not copy its
23
+ // client-specific UI resource metadata into the RemoteShell MCP catalog.
24
+ return Object.freeze({name:tool.name,description:tool.description,
25
+ inputSchema:structuredClone(tool.inputSchema),
26
+ ...(tool.annotations?{annotations:structuredClone(tool.annotations)}:{})});
27
+ }));
28
+ }
29
+ export async function discoverDcCatalog(client,{requestTimeoutMs=12000}={}){
30
+ if(!Number.isSafeInteger(requestTimeoutMs)||requestTimeoutMs<1000||requestTimeoutMs>60000)
31
+ throw Error('DC_CATALOG_TIMEOUT_INVALID');
32
+ if(!client||typeof client.listTools!=='function')throw Error('DC_CATALOG_UNAVAILABLE');
33
+ let cursor,tools=[],pages=0;
34
+ do{
35
+ if(++pages>MAX_PAGES)throw Error('DC_CATALOG_PAGINATION_LIMIT');
36
+ const result=await client.listTools(cursor?{cursor}:{},{timeout:requestTimeoutMs});
37
+ if(!record(result)||!Array.isArray(result.tools))throw Error('DC_CATALOG_INVALID');
38
+ tools.push(...result.tools);
39
+ if(tools.length>MAX_TOOLS)throw Error('DC_CATALOG_SIZE_LIMIT');
40
+ cursor=result.nextCursor;
41
+ if(cursor!==undefined&&(typeof cursor!=='string'||!cursor))throw Error('DC_CATALOG_INVALID');
42
+ }while(cursor);
43
+ return normalizeDcCatalog(tools);
44
+ }
45
+ export function dcCatalogFingerprint(catalog){
46
+ return createHash('sha256').update(stable(catalog)).digest('hex');
47
+ }
48
+ export function diffDcCatalog(previous,current){
49
+ const old=new Map(previous.map(t=>[t.name,t]));
50
+ const now=new Map(current.map(t=>[t.name,t]));
51
+ const added=[...now.keys()].filter(n=>!old.has(n)).sort();
52
+ const removed=[...old.keys()].filter(n=>!now.has(n)).sort();
53
+ const changed=[...now.keys()].filter(n=>old.has(n)&&stable(old.get(n))!==stable(now.get(n))).sort();
54
+ return Object.freeze({added,removed,changed,hasChanges:!!(added.length||removed.length||changed.length)});
55
+ }
56
+ export function wrapDcTool(tool,{expose=false}={}){
57
+ if(!expose)return null; // Discovery never confers execution rights.
58
+ const schema=structuredClone(tool.inputSchema);
59
+ if(schema.type!=='object'||!record(schema.properties)||!validName(tool.name)||
60
+ Object.hasOwn(schema.properties,'device_id')||Object.hasOwn(schema.properties,'root_id'))
61
+ throw Error('DC_CATALOG_SCHEMA_CONFLICT');
62
+ schema.properties.device_id={type:'string',format:'uuid'};
63
+ schema.properties.root_id={type:'string',format:'uuid'};
64
+ schema.required=[...new Set([...(schema.required||[]),'device_id','root_id'])];
65
+ return {name:tool.name,description:tool.description,inputSchema:schema,
66
+ ...(tool.annotations?{annotations:structuredClone(tool.annotations)}:{})};
67
+ }
@@ -0,0 +1,20 @@
1
+ // #249 - DC invocation identity and one-call consent contract (no execution).
2
+ import {createHash} from 'node:crypto';
3
+ import {DC_USER_TOOLS} from './dc-generic-policy.mjs';
4
+ const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
5
+ const fail=()=>{throw Error('DC_RELAY_CONSENT_DENIED')};
6
+ export const DC_RELAY_TOOLS=DC_USER_TOOLS;
7
+ export const dcArgsSha256=args=>createHash('sha256').update(JSON.stringify(args)).digest('hex');
8
+ export function verifyDcConsent({grant,name,args,owner_user_id,connection_id,device_id,root_id,credential_version,grant_version,now=Date.now()}={}){
9
+ if(!grant||typeof grant!=='object'||grant.contract_version!=='rs-dc-relay-v1'||grant.decision!=='ALLOW'||
10
+ grant.executable!==true||!DC_RELAY_TOOLS.includes(name)||grant.tool_id!==name||
11
+ ![owner_user_id,connection_id,device_id,root_id].every(x=>UUID.test(x||''))||
12
+ !Number.isSafeInteger(credential_version)||credential_version<0||
13
+ !Number.isSafeInteger(grant_version)||grant_version<0||
14
+ grant.owner_user_id!==owner_user_id||grant.connection_id!==connection_id||
15
+ grant.device_id!==device_id||grant.root_id!==root_id||
16
+ grant.credential_version!==credential_version||grant.grant_version!==grant_version||
17
+ grant.args_sha256!==dcArgsSha256(args)||!Number.isSafeInteger(grant.expires_at)||
18
+ grant.expires_at<=now||grant.expires_at>now+86400000||!UUID.test(grant.consent_id||''))fail();
19
+ return grant;
20
+ }
@@ -0,0 +1,32 @@
1
+ import {createHash} from 'node:crypto';
2
+
3
+ // Stateless byte offsets over exact UTF-8 snapshot bytes. No server-side cursor to expire.
4
+ const DENY=()=>{throw Error('DEV_PAGE_DENIED');};
5
+ const MAX_TOTAL=1024*1024;
6
+ export function validPageArgs({offset,max_bytes,version}={}){
7
+ if(offset===undefined&&max_bytes===undefined&&version===undefined)return null;
8
+ if(!Number.isSafeInteger(offset)||offset<0||offset>MAX_TOTAL||
9
+ !Number.isSafeInteger(max_bytes)||max_bytes<1||max_bytes>4096||
10
+ (version!==undefined&&(typeof version!=='string'||!/^[a-f0-9]{64}$/.test(version)))||
11
+ offset>0&&version===undefined)DENY();
12
+ return {offset,max_bytes,version};
13
+ }
14
+ export function boundedSnapshotPage(text,{offset,max_bytes,version},policy=0){
15
+ const scope=typeof policy==='number'?{revision:policy}:policy;
16
+ if(typeof text!=='string'||!scope||!Number.isSafeInteger(scope.revision)||scope.revision<0)DENY();
17
+ const identity=JSON.stringify(['owner_user_id','connection_id','device_id','root_id',
18
+ 'credential_version','grant_version','revision'].map(k=>scope[k]??null));
19
+ const bytes=Buffer.from(text,'utf8');
20
+ if(bytes.length>MAX_TOTAL||offset>bytes.length)DENY();
21
+ const digest=createHash('sha256').update('rs-page-v1\0').update(identity).update('\0').update(bytes).digest('hex');
22
+ if(version!==undefined&&version!==digest)throw Error('DEV_PAGE_STALE');
23
+ // Byte offsets must be exact UTF-8 boundaries; don't silently skip bytes.
24
+ if(offset>0&&offset<bytes.length&&(bytes[offset]&0xc0)===0x80)DENY();
25
+ let end=Math.min(bytes.length,offset+max_bytes);
26
+ if(end<bytes.length)while(end>offset&&(bytes[end]&0xc0)===0x80)end--;
27
+ if(end===offset&&offset<bytes.length)DENY();
28
+ const next=end<bytes.length?end:null;
29
+ return Object.freeze({text:bytes.subarray(offset,end).toString('utf8'),offset,
30
+ next_offset:next,total_bytes:bytes.length,version:digest,
31
+ truncated:next!==null,complete:next===null});
32
+ }
@@ -0,0 +1,56 @@
1
+ // #242: CP is the owner-bound source of exclusion rules. No cache: every task
2
+ // receives the current revision or is refused before Agent dispatch.
3
+ const UUID=x=>typeof x==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(x);
4
+ const version=x=>Number.isSafeInteger(x)&&x>=0;
5
+ export const DEFAULT_EXCLUSIONS=Object.freeze(['.ssh','.gnupg','.aws','.kube','.config/gcloud','.config/gh','.env','.npmrc','.git-credentials']);
6
+ export const excludedRule=x=>typeof x==='string'&&x.length>0&&x.length<=256&&
7
+ /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(x)&&
8
+ !x.split('/').some(s=>s==='.'||s==='..');
9
+ const match=(path,rule)=>path===rule||path.startsWith(rule+'/')||path.includes('/'+rule+'/')||path.endsWith('/'+rule);
10
+ export function validateExclusionPolicy(policy,scope){
11
+ if(!policy||policy.contract_version!=='dev-root-exclusions-v1'||policy.decision!=='ALLOW'||
12
+ !UUID(policy.owner_user_id)||!UUID(policy.connection_id)||!UUID(policy.device_id)||!UUID(policy.root_id)||
13
+ !version(policy.credential_version)||!version(policy.grant_version)||
14
+ !version(policy.revision)||policy.semantics!=='exact-and-descendants'||
15
+ policy.glob_supported!==false||policy.negation_supported!==false||
16
+ !Array.isArray(policy.rules)||policy.rules.length>64||
17
+ !Array.isArray(policy.defaults)||JSON.stringify(policy.defaults)!==JSON.stringify(DEFAULT_EXCLUSIONS)||
18
+ policy.rules.some(x=>!excludedRule(x))||new Set(policy.rules).size!==policy.rules.length||
19
+ scope&&Object.entries(scope).some(([k,v])=>policy[k]!==v))throw Error('EXCLUSION_POLICY_DENIED');
20
+ return Object.freeze({...policy,rules:Object.freeze([...policy.rules]),defaults:DEFAULT_EXCLUSIONS});
21
+ }
22
+ export function excludedPath(path,policy){
23
+ if(path==='.')return false;
24
+ // Filesystem entries may have spaces/Unicode or Git quoted names; omit them
25
+ // instead of failing an otherwise permitted directory search/listing.
26
+ if(!excludedRule(path))return true;
27
+ const p=validateExclusionPolicy(policy);
28
+ return [...p.defaults,...p.rules].some(r=>match(path,r));
29
+ }
30
+ export function assertAllowedPath(path,policy){
31
+ if(excludedPath(path,policy))throw Error('EXCLUSION_PATH_DENIED');
32
+ return true;
33
+ }
34
+ export function createGatewayExclusionConsumer({baseUrl,secret,fetchImpl=fetch}={}){
35
+ let endpoint;
36
+ try{const url=new URL(baseUrl);if(url.protocol!=='https:'||url.pathname!=='/'||url.search||url.hash||url.username||url.password)throw Error();
37
+ // DEV-only CP listener shares this OCI host with Gateway; Nginx blocks public access.
38
+ endpoint='http://127.0.0.1:18766/dev/api/internal/gateway/root-exclusions';
39
+ }catch{throw Error('EXCLUSION_CONFIG_DENIED');}
40
+ if(typeof secret!=='string'||secret.length<32||typeof fetchImpl!=='function')throw Error('EXCLUSION_CONFIG_DENIED');
41
+ return Object.freeze({async get(scope){
42
+ if(!scope||!['owner_user_id','connection_id','device_id','root_id'].every(k=>UUID(scope[k]))||
43
+ !version(scope.credential_version)||!version(scope.grant_version))throw Error('EXCLUSION_POLICY_DENIED');
44
+ const d={owner_user_id:scope.owner_user_id,connection_id:scope.connection_id,
45
+ device_id:scope.device_id,root_id:scope.root_id,
46
+ credential_version:scope.credential_version,grant_version:scope.grant_version};
47
+ try{
48
+ const res=await fetchImpl(endpoint,{method:'POST',redirect:'manual',
49
+ headers:{authorization:'Bearer '+secret,'content-type':'application/json',accept:'application/json'},
50
+ body:JSON.stringify(d),signal:AbortSignal.timeout(2000)});
51
+ if(res.status!==200||!/^application\/json(?:\s*;|\s*$)/i.test(res.headers.get('content-type')||''))throw Error();
52
+ const body=await res.text();if(body.length>8000)throw Error();
53
+ return validateExclusionPolicy(JSON.parse(body),d);
54
+ }catch{throw Error('EXCLUSION_POLICY_UNAVAILABLE');}
55
+ }});
56
+ }
@@ -50,4 +50,3 @@ export function validateSyntheticWriteTool(call,{enabled=false}={}){
50
50
  if(Buffer.byteLength(JSON.stringify(args))>65536)deny(ERROR_CODES.ARGUMENTS_DENIED);
51
51
  return Object.freeze({name:call.name,arguments:Object.freeze(Object.fromEntries(keys.map(key=>[key,args[key]])))});
52
52
  }
53
-
@@ -0,0 +1,39 @@
1
+ // Read the private credential created by the OCI DEV pairing flow.
2
+ // This adapter is opt-in to the L2 DEV agent; it never copies or rewrites it.
3
+ import {lstatSync,readFileSync} from 'node:fs';
4
+ import {dirname,resolve} from 'node:path';
5
+ import {homedir} from 'node:os';
6
+ import {inspectWindowsCredentialAcl} from '../../bin/windows-credential-boundary.mjs';
7
+
8
+ const OCI_DEV_BASE='https://ailab-remoteshell.duckdns.org/dev/';
9
+ const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10
+ const TOKEN=/^[A-Za-z0-9._~-]{24,2048}$/;
11
+ const deny=()=>{throw Error('L2_DEV_CREDENTIAL_DENIED');};
12
+
13
+ export function readL2DevOciCredential(file,{lstat=lstatSync,readFile=readFileSync,uid=process.getuid?.(),
14
+ os=process.platform,home=homedir(),inspectWindows=inspectWindowsCredentialAcl}={}){
15
+ let raw;
16
+ try{
17
+ if(os==='win32'){
18
+ // NTFS mode bits and Unix UID are not access controls on Windows.
19
+ // Never silently skip validation or fall back to permissive POSIX checks.
20
+ if(inspectWindows({file,home,os})?.restrictedAcl!==true)deny();
21
+ }else{
22
+ if(os!=='linux'&&os!=='darwin'||typeof file!=='string'||!file.startsWith('/')||
23
+ resolve(file)!==file||file.includes('\0'))deny();
24
+ const parent=lstat(dirname(file)),stat=lstat(file);
25
+ if(!parent.isDirectory()||parent.isSymbolicLink()||parent.uid!==uid||
26
+ (parent.mode&0o777)!==0o700||!stat.isFile()||stat.isSymbolicLink()||
27
+ stat.uid!==uid||(stat.mode&0o777)!==0o600||stat.size>8192)deny();
28
+ }
29
+ raw=readFile(file,'utf8');
30
+ }catch{deny();}
31
+ let data;
32
+ try{data=JSON.parse(raw);}catch{deny();}
33
+ const keys=Object.keys(data||{}).sort();
34
+ if(!data||Array.isArray(data)||Object.getPrototypeOf(data)!==Object.prototype||
35
+ keys.join(',')!=='base,device_credential,device_id,sequence,version'||
36
+ data.version!==1||data.base!==OCI_DEV_BASE||!UUID.test(data.device_id||'')||
37
+ !TOKEN.test(data.device_credential||'')||!Number.isSafeInteger(data.sequence)||data.sequence<0)deny();
38
+ return Object.freeze({device_id:data.device_id,credential:data.device_credential});
39
+ }
@@ -0,0 +1,15 @@
1
+ import {lstatSync,readFileSync} from 'node:fs';
2
+ import {dirname} from 'node:path';
3
+ import {secret} from '../../shared/lib/config.mjs';
4
+
5
+ export function readPrivateP2Credential(filename){
6
+ const credentialFile = filename;
7
+ const fileStat = lstatSync(credentialFile);
8
+ if (!fileStat.isFile() || fileStat.isSymbolicLink() || (fileStat.mode & 0o777) !== 0o600) throw new Error('P2 device credential file must be private');
9
+ const parentStat = lstatSync(dirname(credentialFile));
10
+ if (!parentStat.isDirectory() || parentStat.isSymbolicLink() || (parentStat.mode & 0o777) !== 0o700) throw new Error('P2 device credential directory must be private');
11
+ const parsed = JSON.parse(readFileSync(credentialFile, 'utf8'));
12
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || Object.keys(parsed).some(key => !['device_id', 'credential'].includes(key))) throw new Error('Invalid P2 device provisioning');
13
+ if (typeof parsed.device_id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(parsed.device_id)) throw new Error('Invalid P2 device provisioning');
14
+ return {device_id: parsed.device_id, credential: secret(parsed.credential, 'P2 device credential')};
15
+ }
@@ -0,0 +1,25 @@
1
+ import {spawn} from 'node:child_process';
2
+ const DENY=()=>{throw Error('DEV_DOGFOOD_PROCESS_DENIED');};
3
+ const uuid=x=>typeof x==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(x);
4
+ export function createDevDogfoodProcesses({rootId,maxProcesses=4,maxRunMs=120000,maxOutputBytes=8192,spawnImpl=spawn}={}){
5
+ if(!uuid(rootId)||!Number.isSafeInteger(maxProcesses)||maxProcesses<1||maxProcesses>8||!Number.isSafeInteger(maxRunMs)||maxRunMs<1000||maxRunMs>300000||!Number.isSafeInteger(maxOutputBytes)||maxOutputBytes<256||maxOutputBytes>16384)DENY();
6
+ const rows=new Map(),activeByKey=new Map();
7
+ const MAX_ROWS=128,RETAIN_MS=5*60*1000;
8
+ const clean=()=>{const t=Date.now();
9
+ for(const [id,row] of rows){
10
+ if(row.state!=='running'&&t-row.finishedAt>RETAIN_MS){
11
+ row.workspace?.cleanup();rows.delete(id);if(activeByKey.get(row.workKey)===id)activeByKey.delete(row.workKey);
12
+ }
13
+ }
14
+ if(rows.size>MAX_ROWS)for(const [id,row] of rows){
15
+ if(row.state!=='running'){row.workspace?.cleanup();rows.delete(id);if(activeByKey.get(row.workKey)===id)activeByKey.delete(row.workKey);}
16
+ if(rows.size<=MAX_ROWS)break;
17
+ }
18
+ };
19
+ function key({deviceId,sessionId}){if(!uuid(deviceId)||!uuid(sessionId))DENY();return `${deviceId}:${sessionId}`;}
20
+ return Object.freeze({
21
+ close({deviceId,sessionId}={}){const owner=key({deviceId,sessionId});for(const row of rows.values())if(row.owner===owner&&row.state==='running'){row.state='stopped';row.finishedAt=Date.now();clearTimeout(row.timer);
22
+ try{if(row.child.pid&&process.platform!=='win32')process.kill(-row.child.pid,'SIGTERM');else row.child.kill('SIGTERM');}catch{}}},
23
+ count(){return rows.size;}
24
+ });
25
+ }
@@ -0,0 +1,64 @@
1
+ import {excludedPath,assertAllowedPath} from '../../shared/lib/dev-root-exclusions.mjs';
2
+ // L3 D1 DEV-only local file operations. This module does not grant a remote user
3
+ // access; Gateway/CP must authorize owner, device, approved root and tool first.
4
+ import {lstatSync,realpathSync,readdirSync} from 'node:fs';
5
+ import {resolve,relative,sep,join} from 'node:path';
6
+ const DENY=()=>{throw Error('DEV_DOGFOOD_ROOT_DENIED');};
7
+ const CHECK=/^[A-Za-z0-9._/-]{1,256}$/;
8
+ function rootPath(root){
9
+ if(typeof root!=='string'||!root.startsWith('/')||root==='/'||root.includes('\0'))DENY();
10
+ const p=resolve(root);
11
+ if(p!==root||p==='/'||lstatSync(p).isSymbolicLink())DENY();
12
+ const s=lstatSync(p);
13
+ if(!s.isDirectory()||s.uid!==process.getuid?.())DENY();
14
+ const canonical=realpathSync(p);
15
+ if(canonical!==p)DENY();
16
+ return canonical;
17
+ }
18
+ function at(root,name){
19
+ if(typeof name!=='string'||!CHECK.test(name)||name.startsWith('/')||
20
+ name.split('/').some(x=>x==='..'||x===''))DENY();
21
+ const p=resolve(root,name),r=relative(root,p);
22
+ if(r==='..'||r.startsWith('..'+sep)||r.startsWith('/'))DENY();
23
+ let cur=root;
24
+ for(const part of name.split('/')){
25
+ if(part==='.')continue;
26
+ cur=join(cur,part);
27
+ const st=lstatSync(cur);
28
+ if(st.isSymbolicLink()||!st.isDirectory()&&!st.isFile())DENY();
29
+ }
30
+ return p;
31
+ }
32
+ export function devDogfoodRead({root,path,tool='list_directory',exclusion_policy}={}){
33
+ const base=rootPath(root),p=at(base,path);
34
+ if(exclusion_policy)assertAllowedPath(path,exclusion_policy);
35
+ if(tool==='list_directory'){
36
+ if(!lstatSync(p).isDirectory())DENY();
37
+ return readdirSync(p,{withFileTypes:true}).slice(0,101).map(d=>{
38
+ if(d.isSymbolicLink()||exclusion_policy&&excludedPath(path==='.'?d.name:path+'/'+d.name,exclusion_policy))return null;
39
+ return {name:d.name,type:d.isDirectory()?'directory':d.isFile()?'file':'other'};
40
+ }).filter(Boolean).slice(0,100);
41
+ }
42
+ DENY();
43
+ }
44
+ export function devDogfoodSearch({root,path='.',pattern,maxResults=20,exclusion_policy}={}){
45
+ if(typeof pattern!=='string'||pattern.length<1||pattern.length>128||
46
+ /[\x00-\x1f\x7f]/.test(pattern)||!Number.isInteger(maxResults)||maxResults<1||maxResults>50)DENY();
47
+ const base=rootPath(root),start=at(base,path);
48
+ if(exclusion_policy)assertAllowedPath(path,exclusion_policy);
49
+ if(!lstatSync(start).isDirectory())DENY();
50
+ const results=[],pending=[{dir:start,depth:0}];let scanned=0;
51
+ while(pending.length&&scanned<200&&results.length<maxResults){
52
+ const {dir,depth}=pending.pop();
53
+ const entries=readdirSync(dir,{withFileTypes:true});
54
+ for(const entry of entries){
55
+ if(++scanned>200||results.length>=maxResults)break;
56
+ if(entry.isSymbolicLink())continue;
57
+ const full=join(dir,entry.name),rel=relative(base,full);
58
+ if(exclusion_policy&&excludedPath(rel,exclusion_policy))continue;
59
+ if(entry.isDirectory()&&depth<3)pending.push({dir:full,depth:depth+1});
60
+ if(entry.isFile()&&entry.name.toLowerCase().includes(pattern.toLowerCase()))results.push({path:rel});
61
+ }
62
+ }
63
+ return {matches:results,scanned,truncated:pending.length>0||scanned>=200};
64
+ }
@@ -0,0 +1,113 @@
1
+ import {verifyDcConsent} from '../../shared/lib/dev-dc-relay-contract.mjs';
2
+ import {isDcPublic} from '../../shared/lib/dc-generic-policy.mjs';
3
+ import {validateDcRelayArgs} from '../dc/dev-dc-relay.mjs';
4
+ import {validPageArgs} from '../../shared/lib/dev-paged-output.mjs';
5
+ import {validateExclusionPolicy,assertAllowedPath} from '../../shared/lib/dev-root-exclusions.mjs';
6
+ import {devDogfoodRead,devDogfoodSearch} from './dev-dogfood-read.mjs';
7
+ import {executeDevDogfoodWrite} from './dev-dogfood-write.mjs';
8
+ import {devReadTools} from './dev-read-tools.mjs';
9
+ import {validateR4AgentTool,executeR4AgentTool} from './dev-r4-file-task.mjs';
10
+ import {validateDevFileAgentTool,executeDevFileAgentTool} from './dev-file-task.mjs';
11
+ const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12
+ const plain=x=>!!x&&typeof x==='object'&&!Array.isArray(x)&&Object.getPrototypeOf(x)===Object.prototype;
13
+ const pathAllowedForGit=p=>typeof p==='string'&&p.length<=256&&
14
+ (p==='.'||/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(p))&&
15
+ (p==='.'||!p.split('/').some(x=>x==='..'||x==='.'));
16
+
17
+ export function devDogfoodTaskEnvelope(value,{sessionId,rootId,deviceId}={}){
18
+ if(!plain(value)||Object.keys(value).sort().join(',')!=='request_id,session_id,state,tool'||
19
+ !UUID.test(value.request_id||'')||value.session_id!==sessionId||value.state!=='dispatched'||
20
+ !plain(value.tool)||Object.keys(value.tool).sort().join(',')!=='arguments,name'||!plain(value.tool.arguments)||
21
+ value.tool.arguments.root_id!==rootId||!UUID.test(rootId||''))throw Error('DEV_DOGFOOD_TASK_DENIED');
22
+ const a=value.tool.arguments,name=value.tool.name;
23
+ if(a.dc_relay===true){
24
+ if(!isDcPublic(name)||Object.keys(a).sort().join(',')!=='dc_args,dc_relay,root_id'||
25
+ !plain(a.dc_args)||rootId!==deviceId)throw Error('DC_RELAY_DENIED');
26
+ // Device identity and MCP tool arguments are already validated at the Gateway.
27
+ // The Agent forwards them without a second RS command approval.
28
+ return Object.freeze({request_id:value.request_id,session_id:value.session_id,state:value.state,
29
+ tool:Object.freeze({name,arguments:Object.freeze({...a})})});
30
+ }
31
+ if(a.file_authorization){
32
+ validateDevFileAgentTool(value.tool,{rootId,sessionId,deviceId:deviceId||a.file_authorization.device_id});
33
+ return Object.freeze({request_id:value.request_id,session_id:value.session_id,
34
+ state:value.state,tool:Object.freeze({name,arguments:Object.freeze({...a})})});
35
+ }
36
+ if(a.r4_authorization){
37
+ validateR4AgentTool(value.tool,{rootId,sessionId,deviceId:a.r4_authorization.device_id});
38
+ return Object.freeze({request_id:value.request_id,session_id:value.session_id,
39
+ state:value.state,tool:Object.freeze({name,arguments:Object.freeze({...a})})});
40
+ }
41
+
42
+ const r3=['write_file','edit_block','delete_file'].includes(name);
43
+ const fixture=/^r3-e2e-fixture\/[A-Za-z0-9_-][A-Za-z0-9_.-]*\.(?:mjs|js|cjs|json|md|txt)$/.test(a.path||'');
44
+ if(r3&&!fixture)
45
+ throw Error('DEV_DOGFOOD_TASK_DENIED');
46
+ const schemas={
47
+ list_directory:{required:['path','root_id'],optional:[]},
48
+ start_search:{required:['path','pattern','root_id'],optional:['searchType']},
49
+ search_content:{required:['path','query','regex','limit','offset','root_id'],optional:[]},
50
+ git_status:{required:['path','root_id'],optional:[]},
51
+ git_diff:{required:['path','root_id'],optional:['file','offset','max_bytes','version']},
52
+ write_file:{required:['content','path','root_id'],optional:[]},
53
+ edit_block:{required:['expectedHash','new_string','old_string','path','root_id'],optional:[]},
54
+ delete_file:{required:['expectedHash','path','root_id'],optional:[]}
55
+ };
56
+ const schema=schemas[name];
57
+ if(name==='git_diff')validPageArgs({offset:a.offset,max_bytes:a.max_bytes,version:a.version});
58
+ if(!schema||schema.required.some(k=>a[k]===undefined)||
59
+ Object.keys(a).some(k=>!schema.required.includes(k)&&!schema.optional.includes(k))||
60
+ name==='start_search'&&a.searchType!==undefined&&a.searchType!=='files'||
61
+ name==='git_status'&&(!pathAllowedForGit(a.path))||name==='git_diff'&&(
62
+ !pathAllowedForGit(a.path)||a.file!==undefined&&(
63
+ typeof a.file!=='string'||a.file.length>256||a.file.startsWith('/')||
64
+ !/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(a.file)||
65
+ a.file.split('/').includes('..')))||
66
+ name==='search_content'&&(
67
+ typeof a.query!=='string'||a.query.length>128||a.query.length===0||
68
+ /[\x00-\x1f\x7f]/.test(a.query)||typeof a.regex!=='boolean'||
69
+ !Number.isInteger(a.limit)||a.limit<1||a.limit>100||
70
+ !Number.isInteger(a.offset)||a.offset<0||a.offset>10000))throw Error('DEV_DOGFOOD_TASK_DENIED');
71
+ const args=Object.freeze({...a});return Object.freeze({request_id:value.request_id,session_id:value.session_id,state:value.state,tool:Object.freeze({name,arguments:args})});
72
+ }
73
+
74
+ // Called only for tasks delivered over the authenticated L2 DEV Agent session.
75
+ // root_id is compared with a local mapping; absolute paths never travel on wire.
76
+ export async function executeDevDogfoodTask({tool,rootId,root,client,deviceId,sessionId,processes,exclusion_policy,requirePolicy=false}={}){
77
+ if(!tool||!tool.arguments||tool.arguments.root_id!==rootId)return null;
78
+ const a=tool.arguments;
79
+ if(requirePolicy&&!exclusion_policy)throw Error('EXCLUSION_POLICY_DENIED');
80
+ if(exclusion_policy){
81
+ validateExclusionPolicy(exclusion_policy,{device_id:deviceId,root_id:rootId});
82
+ assertAllowedPath(a.path??a.repo_path,exclusion_policy);
83
+ if(a.test_path)assertAllowedPath(a.test_path,exclusion_policy);
84
+ if(tool.name==='git_diff'&&a.file)
85
+ assertAllowedPath(a.path==='.'?a.file:a.path+'/'+a.file,exclusion_policy);
86
+ }
87
+ if(a.file_authorization)
88
+ return executeDevFileAgentTool({tool,root,rootId,deviceId,sessionId});
89
+ if(a.r4_authorization)return executeR4AgentTool({tool,root,rootId,client,deviceId,sessionId,processes});
90
+ if(tool.name==='list_directory'){
91
+ if(typeof a.path!=='string'||tool.name==='list_directory'&&
92
+ Object.keys(a).sort().join(',')!=='path,root_id')throw Error('ARGUMENTS_DENIED');
93
+ return JSON.stringify(devDogfoodRead({root,path:a.path,tool:tool.name,exclusion_policy}));
94
+ }
95
+ if(['search_content','git_status','git_diff'].includes(tool.name)){
96
+ if(tool.name==='search_content'&&(
97
+ typeof a.query!=='string'||a.query.length===0||a.query.length>128||
98
+ typeof a.regex!=='boolean'||!Number.isSafeInteger(a.limit)||a.limit<1||a.limit>100||
99
+ !Number.isSafeInteger(a.offset)||a.offset<0||a.offset>10000)||
100
+ tool.name!=='search_content'&&!pathAllowedForGit(a.path))throw Error('ARGUMENTS_DENIED');
101
+ return JSON.stringify(await devReadTools({root,name:tool.name,path:a.path,
102
+ ...(tool.name==='search_content'?{query:a.query,regex:a.regex,limit:a.limit,offset:a.offset}:{}),
103
+ ...(tool.name==='git_diff'?{file:a.file,page:validPageArgs(a)}:{}),exclusion_policy}));
104
+ }
105
+ if(tool.name==='start_search'){
106
+ if(!['path,pattern,root_id','path,pattern,root_id,searchType'].includes(Object.keys(a).sort().join(','))||
107
+ typeof a.path!=='string'||a.searchType!==undefined&&a.searchType!=='files')throw Error('ARGUMENTS_DENIED');
108
+ return JSON.stringify(devDogfoodSearch({root,path:a.path,pattern:a.pattern,maxResults:50,exclusion_policy}));
109
+ }
110
+ if(['write_file','edit_block','delete_file'].includes(tool.name))
111
+ return executeDevDogfoodWrite({root,tool,client});
112
+ throw Error('TOOL_DENIED');
113
+ }